Leetcode 53. Maximum Subarray
1 min readAug 18, 2018
This is a classic DP problem and is really good. Basically we follow a standard approach:
- Define: let
largest[i]be the largest sum of a contiguous subarray ending at position i ofnums. - Find recurrence equation:
largest[i] = nums[i] + largest[i-1]iflargest[i-1] > 0, andlargest[i] = nums[i]otherwise, since it makes no sense to includenums[i]in previous contiguous subarray if previous sum is negative — I can simply start over fromnums[i]. - Implement.
Get HAOYU LEI’s stories in your inbox
Join Medium for free to get updates from this writer.
Pseudocode (indexing start from 1):
ALGORITHM maxSubArray(nums)
For i from 2 to len(nums) do
largest[i] = largest[i-1] > 0? nums[i] + largest[i-1] : nums[i]
return max(nums)



