Leetcode Note: Maximum Subarray (Maximum substring and problem)
I. Description
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 largestsum = 6.
Ii. Question Analysis
You can use dynamic planning to solve the problem. The time complexity is O (n ). Assuming that0, .., kThe largest andsum[k]Later, then0, ..., k+1Sum [k + 1] is divided into the following two situations:
1) ifsum[k]>=0, Thensum[k+1]=sum[k]+A[k+1].
2) Ifsum[k]<0, Create another SubArraysum[k+1]=A[k+1].
In the calculation process, use a variablemaxsumFor storagesumThe maximum value.sumThe value is updated, and the variable is returned.
Iii. Sample Code
int maxSubArray(int A[], int n) { if (n <= 0) return 0; int sum = 0; int maxsum = INT_MIN; for (int i = 0; i < n; i++) { sum += A[i]; if (sum > maxsum) maxsum = sum; if (sum < 0) sum = 0; } return maxsum; }
Iv. Summary
This is a basic dynamic planning question, although there are many other ways to achieve it.