Back to Dashboard
Smallest Subarray With a Greater Sum
MediumProblem Statement
Given an array of positive integers and a number ‘S,’ find the length of the smallest contiguous subarray whose sum is greater than or equal to 'S'. Return 0 if no such subarray exists.
Examples
Example 1:
- Input:
arr = [2, 1, 5, 2, 3, 2], S = 7 - Output:
2
Approach 1 Sliding Window:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
var windowStart = 0;
var minLength = Integer.MAX_VALUE;
var windowSum = 0;
for (int windowEnd = 0; windowEnd < nums.length; windowEnd ++) {
windowSum += nums[windowEnd];
while (windowSum >= target) {
minLength = Math.min((windowEnd - windowStart + 1), minLength);
windowSum -= nums[windowStart];
windowStart ++;
}
}
return minLength != Integer.MAX_VALUE
? minLength
: 0;
}
}