Problem
Problem page: https://leetcode.com/problems/maximum-subarray/
Topics: Divide and Conquer, Array, Dynamic Programming
Difficulty: Medium
Similar problems: (M) Best Time to Buy and Sell Stock, (M) Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
[-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray[4,-1,2,1]has the largest sum =6.More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Analysis
Finding the contiguous subarray with the largest sum is another classic. This is a bit like Gas Station in what happens when sum drops below 0 after we add the element at k to the current subarray (the element at k must itself be negative). Carrying sum forward won't help at k+1. Even dropping some elements from the left end of the subarray won't help. Their sum must be greater than 0, so dropping them would make things worse. We might as well reset sum to 0 and start adding again at k+1.
Picture an irregular waveform. Starting at some point on the x-axis, sum is the area you accumulate as you move along the axis. The area above the x-axis is the useful area, and the area below it is negative.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-maximum-subarray/
