最大子序列,动态规划算法:使用一个临时值tmpSum保存遍历后的子序列和,然后与maxSum进行比较;
代码如下:
public static void main(String[] args) {
//快排测试
TestQuickSort();
//数组最大子序列测试
TestMaxSubSequence();
}
public static void TestMaxSubSequence(){
int []arr = {-7,-6,5,8,-3,1,-4,18,-42};
int res = MaxSubSequence(arr);
System.out.println("the max sub sequence is " + res);
}
public static int MaxSubSequence(int []arr){
int maxSum=0, tmpSum = 0;
for (int i=0;i<arr.length;i++){
tmpSum += arr[i];
if(tmpSum >= maxSum){
maxSum = tmpSum;
}else if(tmpSum < 0){
tmpSum = 0;
}
}
return maxSum;
}