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
.
思路:动态规划
辅助数组sum[n],sum[i]表示以下标为i的数字结尾的最大连续数字和,其中maxSum记录最大和即可。
代码:
int maxSubArray(int A[], int n) {
if(n<=0 || A==NULL)
{
return 0;
}
int *sum=new int [n];
int maxSum=A[0];
sum[0]=A[0];
for(int i=1; i<n; ++i)
{
if(sum[i-1]+A[i] < A[i])
{
sum[i]=A[i];
}
else
{
sum[i]=sum[i-1]+A[i];
}
if(maxSum < sum[i])
{
maxSum=sum[i];
}
}
return maxSum;
}