最大连续序列之和问题,思路就是保持两个变量,一个记录到当前位置最大的和(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)); } }
作者:hellobinfeng 发表于2013-12-3 2:38:26 原文链接
阅读:103 评论:0 查看评论