forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbhyun-kim.py
More file actions
31 lines (22 loc) · 851 Bytes
/
bhyun-kim.py
File metadata and controls
31 lines (22 loc) · 851 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
53. Maximum Subarray
https://leetcode.com/problems/maximum-subarray
Solution:
To solve this problem, we can use the Kadane's algorithm.
We keep track of the current sum and the maximum sum.
We iterate through the array and update the current sum and maximum sum.
If the current sum is greater than the maximum sum, we update the maximum sum.
We return the maximum sum at the end.
Time complexity: O(n)
- We iterate through each element in the array once.
Space complexity: O(1)
- We use a constant amount of extra space.
"""
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum