Maximum subarray
Total accepted: 28381 total submissions: 83696 my submissions
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.
If the array is set to a [n] And the DP [n-1] is the largest subsequence of the first n-1 number, then DP [N] = DP [n-1]> 0? DP [n-1] + A [n]: A [n]. This algorithm is used to scan the sum of consecutive subsequences from the leftmost to rightmost.
How can we find the largest subsequence. Calculate maxsum = max {DP [N] And maxsum} each time to save the largest subsequence.
For element N = 0, sum = A [0], the maximum sequence is maxsum = A [0,
According to the cyclic immutability. For N
1. Set the sum of a continuous subsequence of DP [n-1] to a [n-1] = DP [n-1]. assume that a [n-1] is the subsequence and. if a [n-1]> = 0, then a [n-1] + A [n] is the maximum value of the {A [n-1], a [n]} sequence. This means that the continuous subsequence continues to increase and a [n] is included in this continuous subsequence. The value of this continuous subsequence also increases accordingly.
2. If a [n-1] <0, a [n] is the maximum value of this continuous subsequence. This means that a new continuous subsequence is restarted.
3. If maxsum is the maximum continuous subsequence sum, maxsum = max (A [n], maxsum) can be used to calculate the maximum values of the previous continuous subsequence and the current subsequence, this function ensures that at N, maxsum is still a [0]... the maximum continuous subsequence of a [n] and.
At the end of N, it still satisfies the circular immutability, and the algorithm is proved complete.
class Solution {public: int maxSubArray(int A[], int n) { int sum=A[0],maxSum=A[0]; for(int i=1;i<n;i++) { if(sum<0) sum=0; sum+=A[i]; maxSum=max(sum,maxSum); } return maxSum; }};
Leetcode maximum subarray maximum subsequence