思路:定一一个下标索引,当sum和目前遍历到的数想加大于0,就加上这个数。如果小于0,就让sum等于这个数的下一个数。遍历期间一直更新max
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int start=0;
int max=Integer.MIN_VALUE;
int sum=0;
while(start<array.length){
if(array[start]+sum>0){
sum+=array[start];
max=Math.max(max,sum);
start++;
}
else{
if(start<array.length-1){
max=Math.max(max,array[start]); //加这句是为了避免全是负数的情况下出错
sum=array[start+1];
max=Math.max(sum,max);
}
start+=2;
}
}
return max;
}
}