题目:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。
思路:从头到尾逐个累加,保存两个值:当前和&最大和。
代码:
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int len=array.length; if(len<=0){ return 0; } int tempSum=0; int maxSum=array[0]; for(int begin=0;begin<len;begin++){ tempSum=array[begin]; if(tempSum>maxSum){ maxSum=tempSum; } if(begin<len-1){ for(int i=begin+1;i<len;i++){ tempSum+=array[i]; if(tempSum>maxSum){ maxSum=tempSum; } } } } return maxSum; }}