Continuous Subarray Sum

Source

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 their are duplicate answer, return anyone)

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

题解

和题 Maximum Subarray 几乎一模一样,只是返回值要求不一样

Java

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) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        int start=0;

        result.add(0);
        result.add(0);
        int sum = A[0];
        int max =sum;

        for(int i=1; i<A.length; i++) {
            if(sum>max){
                result.set(0, start);
                result.set(1, i-1);
                max=sum;
            }

            if(sum<0){
                sum=0;
                start=i;
            }

            sum+=A[i];
        }  

        if(sum>max){
            result.set(0, start);
            result.set(1, A.length-1);
        }

        return result;
    }
}