Moderate 最大连续序列之和 @CareerCup

来源:互联网 发布:景观大数据破解 编辑:程序博客网 时间:2024/06/08 19:50

最大连续序列之和问题,思路就是保持两个变量,一个记录到当前位置最大的和(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.EXAMPLEInput: {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));}}