Sliding window

Minimum Subarray Sum

Estimated reading: 1 minute 37 views

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Input:

  • nums = [2, 3, 1, 2, 4, 3]
  • target = 7

Output:

  • Result = 2

Explanation:

We are looking for the smallest contiguous subarray with a sum greater than or equal to 7. The possible subarrays that meet this condition are:

  1. [2, 3, 1, 2] with a sum of 8 (length 4)
  2. [3, 1, 2, 4] with a sum of 10 (length 4)
  3. [2, 4, 3] with a sum of 9 (length 3)
  4. [4, 3] with a sum of 7 (length 2)

Among these, [4, 3] is the smallest subarray with a sum equal to or greater than 7. Its length is 2, which is the minimal length we are looking for.

If no such subarray exists:

If nums = [1, 1, 1, 1] and target = 5, there is no subarray with a sum of at least 5. Therefore, the output would be 0.

				
					public int minSubArrayLen(int targetSum, int[] numbers) {
    int start = 0, end = 0, currentWindowSum = 0;
    int minLength = Integer.MAX_VALUE;

    for (end = 0; end < numbers.length; end++) {
        currentWindowSum += numbers[end];

        while (currentWindowSum >= targetSum) {
            minLength = Math.min(minLength, end - start + 1);
            currentWindowSum -= numbers[start++];
        }
    }

    return minLength == Integer.MAX_VALUE ? 0 : minLength;
}
				
			
Share this Doc

Minimum Subarray Sum

Or copy link

CONTENTS