Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return -1 instead.

Example

Given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

Notes:

  1. Forward two pointers: continuous subarray
  2. Apply template: for-while-forward
  3. time: O(n)
    public int minimumSize(int[] nums, int s) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        int min = Integer.MAX_VALUE;
        int n = nums.length;
        int j = 0;
        int sum = 0;
        for (int i = 0; i < n; ++i) {
            while(j < n && sum < s) {
                sum += nums[j];
                j++;
            }

            if (sum >= s) {
                min = Math.min(min, j-i);
            }

            sum -= nums[i];

            if (j == n && sum < s) {
                break;
            }
        }

        return min == Integer.MAX_VALUE ? -1 : min;
    }

results matching ""

    No results matching ""