连续子数组的最大和
思路:{6, -3, -2, 7, -15, 1, 2, 2},连续子数组的最大和为 8(从第 0 个开始,到第 3 个为止)。
这题要是用动态规划就非常简单,我就不多做解释了,其中res = Math.max(max, res);一定要有!!:
public int FindGreatestSumOfSubArray(int[] array) {
int res = array[0]; //记录当前所有子数组的和的最大值
int max = array[0]; //包含array[i]的连续数组最大值
for (int i = 1; i < array.length; i++) {
max = Math.max(max + array[i], array[i]);
res = Math.max(max, res);//一定要有这个判读!!
}
return res;
}
但是其实我首先想到的并不是使用动态规划的方式,我们可以用total记录累计值,maxSum记录和最大基于思想:
对于一个数A,若是A的左边累计数非负,那么加上A能使得值不小于A,认为累计值对整体和是有贡献的。如果前几项累计值负数,则认为有害于总和,total改为当前值(从当前值开始累加)。此时 若和大于maxSum 则用maxSum记录下来:
public int FindGreatestSumOfSubArray(int[] array) {
if(array.length==0)
return 0;
else{
int total=array[0],maxSum=array[0];
for(int i=1;i<array.length;i++){
if(total>=0)
total+=array[i];
else
total=array[i];
if(total>maxSum)
maxSum=total;
}
return maxSum;
}
}