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 you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解题思路:对A[0]、A[1]...A[n-1]这n个数中求连续子集的最大值
对A[1]、A[2]...A[n-1] 中最大和为All[1],包含A[1]的最大和为Start[1]
那么,All[0]=MAX{A[0],A[0]+Start[1],All[1]}
这里的划分:A[0]与最大和数组有无关系,或者说最大和数组包含不包含A[0]
算法思想是动态规划,从后往前,不去计算已经算过的东西,即“去除冗余”
class Solution {
public:
int maxSubArray(int A[], int n) {
//A[0]
//A[1]...A[n-1] 最大和为All[1]
//包含A[1]的最大的和为Start[1]
if(n<=0)
return 0;
int All,Start;
All=Start=A[n-1];
for(int i=n-2;i>=0;i--)
{
if(A[i]+Start>A[i])
Start=A[i]+Start;
else
Start=A[i];
if(Start>All)
All=Start;
}
return All;
}
};