Title: Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which have the largest sum.
For example, given the array [?2,1,?3,4,?1,2,1,?5,4] ,
The contiguous Subarray has the [4,?1,2,1] largest sum = 6 .
Links: https://leetcode.com/problems/maximum-subarray/
Analysis: This is the sum of the maximal contiguous string, or the largest contiguous subarray of sums.
The simplest of the problem is violence, but the violence is O (n^2), timed out. In addition, dynamic programming can be used to solve the problem, the key is how to convert to dynamic programming, that is, how to express the dynamic programming problem.
we use local[i] to denote the maximum sum of successive sub-arrays ending with a[i] , then local[0] = a[0], local[1] equals either local[0]+a[1] or equals a[1] itself, the key to look at the two who are bigger, So we get recursive local[i+1] = max (Local[i]+a[i], a[i]),,,, The maximum value in the local array is the request. The iterative process does not require an array so the time complexity is O (N) and the spatial complexity is O (1).
Class Solution {public: int maxsubarray (int a[], int n) { if (n = = 0) return 0; int sum = a[0]; Contiguous subarray and maximum value int maxresult = a[0] ending with a[0]; for (int i = 1; i < n; i++) { sum = max (a[i],a[i]+sum); Continuous sub-array and maximum if (Maxresult < sum) ending with a[i] maxresult = sum; } return maxresult;} ;
Leetcode Maximum subarray**