Problem:
Find the contiguous subarray within an array (containing at least one number) which have the largest sum.
For example, given the array[㈢,1,3,4,ㄢ,2,1,5,4],
The contiguous Subarray[4,ㄢ,2,1]Has the largest sum =6.
Several attempts have been made to find that the problem itself has no optimal substructure, but the transformation of the problem: F (j)-The maximal continuous subsequence with s[j] as the tail-but with the optimal substructure , the recursive relationship is as follows:
F (-1) = 0;
F (j) =max (f (j-1) +a[j],a[j]) j>=0;
Therefore, we first solve the solution, and in the solution process to record the current maximum results, as the solution of the problem itself, the code is as follows:
int Maxsubarray (int a[], int n) {int result =-int_max,f=0; for (int i=0;i<n;i++) {F=max (f+a[i],a[i]); Result=max (F,result); } return result;
This article is from the "half-half" blog, be sure to keep this source http://4902717.blog.51cto.com/4892717/1591878
Leetcode Maximum subarray Dynamic Programming implementation