File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments