Subarray Sum II

Description

Given an positive integer array  A and an interval. Return the number of subarrays whose sum is in the range of given interval.

Subarray is a part of origin array with continuous index.

Example

Example 1:

Input: A = [1, 2, 3, 4], start = 1, end = 3
Output: 4
Explanation: All possible subarrays: [1](sum = 1), [1, 2](sum = 3), [2](sum = 2), [3](sum = 3).

Example 2:

Input: A = [1, 2, 3, 4], start = 1, end = 100
Output: 10
Explanation: Any subarray is ok.
Ideas:

O (N) algorithm of the two pointers

In fact need three hands, because it requires additional record from which the starting position plus and has> = start up.

For each of the left point left, right two corresponding points obtained right_start, right_end. The former indicates that the leftmost [left, right_start] subarray is not less than the start point, which indicates that the rightmost [left, right_end] sub-array is not greater than the end point.

right_end - right_start + 1 is the number of legal sub-arrays to left as the left point.

From left to right enumeration left, and right_start, right_end also grows left only to rise, so the time complexity is O (N)

O (NlogN) dichotomy

And obtaining a prefix array, and then for each prefix presum [right], we require two points left_start, left_end. The former indicates that the leftmost [left_start, right] subarray and end point is not greater than the latter indicates that the rightmost [left_end, right] sub-arrays and the start point of not less than.

Enumeration right, we can look for to determine left_start, left_end in presum [0..right] half on.

to sum up

The above two methods are the same, all for an endpoint subarray, further confirmed the endpoints of a range in which an end of the enumeration process, a range of additional endpoints is monotonic, it is possible to use two pointers O ( N) to complete.

You can put two hands and comprehensive look at the dichotomy, but this time the complexity of the theory is the same, there is no great need. These two methods recommend the first, less complex.

public class Solution {
    /**
     * @param A: An integer array
     * @param start: An integer
     * @param end: An integer
     * @return: the number of possible answer
     */
   public int subarraySumII(int[] A, int start, int end) {
        int n = A.length;
        if (n == 0) {
            return 0;
        }

        int[] sum = new int[n + 1];
        int i, l, r, res = 0;
        sum[0] = 0;
        for (i = 1; i <= n; ++i) {
            sum[i] = sum[i - 1] + A[i - 1];
        }

        l = r = 0;
        for (i = 1; i <= n; ++i) {
            while (l < i && sum[i] - sum[l] > end) {
                ++l;
            }

            while (r < i && sum[i] - sum[r] >= start) {
                ++r;
            }

            res += r - l;
        }

        return res;
    }
}

  

Guess you like

Origin www.cnblogs.com/FLAGyuri/p/12078494.html