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 anyone)

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

思路

核心是找subarray maximum sum,所以使用global/local dp求解。只不过这里我们还需要知道具体的subarray,所以我们需要keep track of start index and update it if necessary。

复杂度

time O(n), space O(1)

代码

  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
        // check edge case
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (A == null || A.length == 0) {
            return result;
        }

        // preprocess
        int[] local = new int[2];
        int[] global = new int[2];
        int start = 0;
        local[0] = global[0] = A[0];
        result = new ArrayList<Integer>(Arrays.asList(0,0));

        // main
        for (int i = 1; i < A.length; i++) {
            //local
            int cur = A[i];
            local[i % 2] = Math.max(cur, local[(i-1) % 2] + cur);

            if (local[i % 2] == cur) {
                start = i;
            } 
            //global
            global[i%2] = Math.max(global[(i-1) % 2], local[i%2]);
            if (global[i%2] == local[i%2]) {
                result = new ArrayList<Integer>(Arrays.asList(start, i));
            }
        }
        return result;
    }
}

results matching ""

    No results matching ""