Skip to content

Commit d6a33dd

Browse files
committed
add solution: maximum-subarray
1 parent 23966d5 commit d6a33dd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

maximum-subarray/dusunax.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''
2+
# 53. Maximum Subarray
3+
4+
- use Kadane's Algorithm for efficiently finding the maximum subarray sum.
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(n)
10+
SC: O(1)
11+
```
12+
13+
#### TC is O(n):
14+
- iterating through the list just once to find the maximum subarray sum. = O(n)
15+
16+
#### SC is O(1):
17+
- using a constant amount of extra space to store the current sum and the maximum sum. = O(1)
18+
'''
19+
20+
class Solution:
21+
def maxSubArray(self, nums: List[int]) -> int:
22+
if len(nums) == 1:
23+
return nums[0]
24+
25+
currentSum = 0 # SC: O(1)
26+
maxSum = nums[0] # SC: O(1)
27+
28+
for i in range(len(nums)): # TC: O(n)
29+
currentSum = max(currentSum + nums[i], nums[i]) # TC: O(1)
30+
31+
if currentSum > maxSum: # TC: O(1)
32+
maxSum = currentSum
33+
34+
return maxSum

0 commit comments

Comments
 (0)