File tree 1 file changed +25
-0
lines changed
1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 53. Maximum Subarray
2
+
3
+ ## Kadane's Algothrim
4
+ - Run-time: O(N)
5
+ - Space: O(1)
6
+ - N = Number of nodes in tree
7
+
8
+ Kadane's Algothrim is a good thing to know.
9
+ There are proofs out there explaining why this works if you are interested.
10
+ Overall its a dynamic programming solution at its core.
11
+
12
+ Because the question is asking for a contiguous subarray, we can use the previous sums to find our max sum for a given n.
13
+ The main idea is that there are two choices to be made, whether (previous sum + n) or (n) is larger.
14
+
15
+ ```
16
+ class Solution:
17
+ def maxSubArray(self, nums: List[int]) -> int:
18
+ if len(nums) == 0:
19
+ return 0
20
+ max_sum, prev_sum = nums[0], nums[0]
21
+ for n in nums[1:]:
22
+ prev_sum = max(n, n+prev_sum)
23
+ max_sum = max(max_sum, prev_sum)
24
+ return max_sum
25
+ ```
You can’t perform that action at this time.
0 commit comments