题目描述
例如:给定数组[−2,1,−3,4,−1,2,1,−5,4],其某个连续子数组的最大和为[4,−1,2,1],sum = 4 + (-1)+ 2 + (1) =6
思路:从头开始累加,如果出现负数的情况,则将sum置为0
代码如下:
public class Solution {
public int maxSubArray(int[] A) {
if (A.length == 0)
return 0;
else if (A.length == 1)
return A[0];
else{
int max = A[0];
int sum = 0;
for (int i = 0;i < A.length;i++){
sum = sum + A[i];
if (sum > max)
max = sum;
if (sum < 0)
sum = 0;
}
return max;
}
}
}