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
.
//dp法,sum值处于大于0,则一直求和,如果小于0不求和,直接得给定值。
//即 sum = sum < 0 ? A[i] : sum + A[i];
//得到相应下标办法(当取A[i]时更新开始下标,另种情况更新end下标,并在max_val取值处最终决定。)
int maxSubArray(int A[], int n) {
int max_val = INT_MIN;
int sum = 0;
for(int i = 0; i < n; i++)
{
sum = max(A[i],sum+A[i]);//比较的时A[i],sum+A[i]
max_val = max(max_val,sum);
}
return max_val;
}