Monday, May 20, 2019

Lintcode 402. 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 the minimum one in lexicographical order)

Example

Example 1:
Input: [-3, 1, 3, -3, 4]
Output: [1, 4]
Example 2:
Input: [0, 1, 0, 1]
Output: [0, 3]
Explanation: The minimum one in lexicographical order.

Code (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 List<Integer> continuousSubarraySum(int[] A) {
        // write your code here
        List<Integer> ans = new ArrayList<>();
        if (A == null || A.length == 0) {
            return ans;
        }
        
        int sum = 0;
        int minPreSum = 0;
        int maxSum = Integer.MIN_VALUE;
        int start = -1;
        int end = -1;
        ans.add(-1);
        ans.add(-1);
        
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            
            if (sum - minPreSum > maxSum) {
                maxSum = sum - minPreSum;
                end = i;
                ans.set(0, start + 1);
                ans.set(1, end);
            }
            
            if (sum < minPreSum) {
                minPreSum = sum;
                start = i;
            }
        }
        
        return ans;
    }
}

No comments:

Post a Comment