[LintCode] Continuous Subarray Sum

本文介绍了一种寻找整数数组中最大连续子数组的方法,并给出了详细的算法实现过程。通过跟踪当前子数组的和及其起始和结束位置,可以在O(n)的时间复杂度内找到使总和最大的子数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number(If there are duplicate answers, return anyone).

Example

Give [-3, 1, 3, -3, 4], return [1,4].

Note

  1. 在res初始化时不放两个0进去,res的长度还是0,在for循环里会出问题。

  2. 循环里先判断上一次的结果,再执行sum+=A[i],减少不必要的分支语句。

Solution

public class Solution {
    public ArrayList<Integer> continuousSubarraySum(int[] A) {
        // Write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (A == null || A.length == 0) {
            return res;
        }
        int sum = A[0];
        int max = sum;
        int start = 0, end = 0;
        res.add(0); 
        res.add(0);
        for (int i = 0; i < A.length; i++) {
            if (sum > max) {
                res.set(0, start); 
                res.set(1, i-1); //here the index comes from last loop, so is (i-1)
                max = sum;
            }
            if (sum < 0) {
                start = i;
                end = i;
                sum = 0;
            }
            sum += A[i];
        }
        if (sum > max) {
            res.set(0, start);
            res.set(1, A.length-1);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值