题目
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
.
求最大的子链和。
和最大的子链从头开始到任意位置的和必然大于等于0,否则去掉该部分可以获得更大的和。
所以从头开始扫描,当和小于0时,将头置为此后一个位置,重新开始计算。
代码:
class Solution {
public:
int maxSubArray(int A[], int n) {
int max=A[0],sum=0; //最大和,临时和
int last=0; //当前计算到的位置
while(last<n)
{
sum+=A[last++]; //累加
if(sum>max) //更新最大值
max=sum;
if(sum<0) //小于0时更改头位置,重新求和
sum=0;
}
return max;
}
};