题目:
Find the contiguoussubarray within an array (containing at least one number) which has the largestsum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has thelargest sum = 6.
分析:
对于数组中的任意一个元素i,要求包含i的最大和子串,只需要把以i左邻元素结尾的最大字串、i、以i右邻元素开头的最大子串,这3个串连接起来即可。再简化一下,以某个元素结尾的最大子串和以某个元素开头的最大子串,实际是相互包含的,最大子串的开头元素和结尾元素都是确定的。只需要求得以每个元素结尾的最大子串,再比较它们,即可得到原数组的最大和子串。
代码:
int maxSubArray(int A[], int n) {
int result = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < n; ++i) {
if(sum>0){
sum += A[i] };
}else{
sum = A[i];
}
result = result>sum : result ? sum;
}
return result;
}