Skip to content

Commit 50b313e

Browse files
committed
ID: 53 Maximum Subarray (Dynamic Programming)
1 parent 0acacfb commit 50b313e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given an integer array nums, find the contiguous subarray (containing at least one number)
3+
which has the largest sum and return its sum.
4+
5+
Input: [-2,1,-3,4,-1,2,1,-5,4],
6+
Output: 6
7+
Explanation: [4,-1,2,1] has the largest sum = 6.
8+
'''
9+
from typing import List
10+
class Solution:
11+
''' Approach #1 (Kadane's Algorithm) '''
12+
'''
13+
Simple idea of the Kadane’s algorithm is to look for all positive contiguous segments
14+
of the array (max_ending_here is used for this). And keep track of maximum sum contiguous
15+
segment among all positive segments (max_so_far is used for this).
16+
Each time we get a positive sum compare it with max_so_far and update max_so_far
17+
if it is greater than max_so_far
18+
Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem
19+
'''
20+
def maxSubArray(self, nums: List[int]) -> int:
21+
best = nums[0]
22+
curr = nums[0]
23+
for idx in range(1,len(nums)):
24+
curr = max(curr+nums[idx],nums[idx])
25+
best = max(curr,best)
26+
27+
return best
28+
29+
30+
if __name__ == '__main__':
31+
sol = Solution()
32+
nums = [-2,1,-3,4,-1,2,1,-5,4]
33+
print(sol.maxSubArray(nums))

0 commit comments

Comments
 (0)