最大连续序列之和问题,思路就是保持两个变量,一个记录到当前位置最大的和(maxSum),还有一个记录当前位置的和(curSum)
当curSum+a[i]<0时,curSum重置为0,表示不选择a[i]
如果>=0时,curSum += a[i]
package Moderate;
/**
*
* You are given an array of integers (both positive and negative). Find the continuous sequence with the largest sum. Return the sum.
EXAMPLE
Input: {2, -8, 3, -2, 4, -10}
Output: 5 (i.e., {3, -2, 4} )
译文:
给出一个整数数组(包含正数和负数),找到和最大的连续子序列,返回和。
例子:
输入: {2, -8, 3, -2, 4, -10}
输出: 5 (即, {3, -2, 4} )
*
*/
public class S17_8 {
public static int getMaxSum(int[] a) {
if(a.length == 0){
return 0;
}
int maxSum = 0;
int curSum = 0;
for(int i=0; i<a.length; i++){
if(curSum+a[i] >= 0){
curSum += a[i];
maxSum = Math.max(maxSum, curSum);
}else{
curSum = 0;
}
}
return maxSum;
}
public static void main(String[] args) {
int[] a = {2, -8, 3, -2, 4, -10};
// int[] a = {-10, -8};
System.out.println(getMaxSum(a));
}
}
最大连续子序列求和

本文介绍了一种高效算法来解决最大连续子序列求和问题。通过维护当前和最大和两个变量,在遍历数组过程中更新它们,从而找到具有最大和的连续子序列。
364

被折叠的 条评论
为什么被折叠?



