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;
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论