Saturday, July 11, 2015

Continuous Subarray Sum

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)
Have you met this question in a real interview? 
Yes

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

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 curSum = A[0], maxSum = Integer.MIN_VALUE;
        int start = 0, end = 0;
        ArrayList<Integer> res = new ArrayList<Integer>();
        res.add(0);
        res.add(0);
        for(int i = 1; i < A.length; i++){
            if(maxSum < curSum){
                res.set(0, start);
                res.set(1, i-1);
                maxSum = curSum;
            } 
            if(curSum < 0){
                curSum = 0;
                start = i;
                end = i;
            }
            curSum += A[i];
             
        }
        
        if(maxSum < curSum){
            res.set(0, start);
            res.set(1, A.length - 1);
        }
        return res;
    }
}

No comments:

Post a Comment