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.

Solution:

We could solve this problem by using Sliding Window Two Pointers in O(n) time complexity and O(1) space.

Code:

public class Solution {
    /**
     * @param nums: an array of integers
     * @param s: an integer
     * @return: an integer representing the minimum size of subarray
     */
    public int minimumSize(int[] nums, int s) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int n = nums.length;
        int minLen = Integer.MAX_VALUE;
        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) {
                minLen = Math.min(minLen, j - i);
            }
            sum -= nums[i];
        }
        if (minLen == Integer.MAX_VALUE) {
            return -1;
        }
        return minLen;
    }
}

results matching ""

    No results matching ""