连续子数组求和

给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)

样例

给定 [-3, 1, 3, -3, 4], 返回[1,4].

思路:

如果数组全为负数,则选择其最大的即可。

否则偏历一次,记录以下标i结尾的最大和子数组,如果当前子数组的和小于0,则更新子数组头(即 tb = i+1);如果当前子数组的和比 下标为0--i-1的数组中的最大和大,则更新最大和及其范围。


代码:

public class Solution {
    /**
     * @param A an integer array
     * @return  A list of integers includes the index of the first number and the index of the last number
     */
    public ArrayList<Integer> continuousSubarraySum(int[] A) {
        // Write your code here
        int Rb,Re,Max,tb,ts,MaxId;
        Max = Integer.MIN_VALUE;
        
        MaxId = Rb = Re = ts = tb = 0;
        for(int i=0;i<A.length;++i){
            ts += A[i];
            if(ts < 0){
                tb = i+1;
                ts = 0;
            }else if(ts > Max){//更新最大和及其范围
                Rb = tb;
                Re = i;
                Max = ts;
            }
            if(A[i] > A[MaxId])
                MaxId = i;
        }
        if(Rb==0&&Re==0)
            Rb = Re = MaxId;
        ArrayList<Integer> R = new ArrayList<Integer>();
        R.add(Rb);
        R.add(Re);
        return R;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值