Moderate 最大连续序列之和 @CareerCup

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值