Leetcode 209. Minimum Size Subarray Sum
You are given an array of positive integers nums
and a positive integer target
. Return the minimal length of a contiguous subarray [nums[l], nums[l+1], ..., nums[r-1], nums[r]]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0 instead.
target = 7
, nums = [2,3,1,2,4,3]
2
[4,3]
has the minimal length under the problem constraint.nums
are positive integers.nums
contain zero elements?
nums
can be empty, in which case the answer should be 0.left
and right
) to represent the current window.right
pointer to include more elements and calculate the running sum.target
, record the length of the subarray.left
pointer to see if we can find a smaller subarray that still meets the sum requirement.minLength
to a large value to store the minimum subarray length found.left
pointer starting at 0, and iterate with right
pointer through the array.nums[right]
to the running sum.target
:
minLength
with the smaller value between minLength
and the current window size (right - left + 1
).nums[left]
from the running sum and increment left
pointer.minLength
is unchanged (meaning no valid subarray was found), return 0.minLength
.#include <vector>
#include <algorithm>
#include <climits>
int minSubArrayLen(int target, std::vector<int>& nums) {
int n = nums.size();
int minLength = INT_MAX;
int left = 0, sum = 0;
for (int right = 0; right < n; ++right) {
sum += nums[right];
while (sum >= target) {
minLength = std::min(minLength, right - left + 1);
sum -= nums[left++];
}
}
return (minLength == INT_MAX) ? 0 : minLength;
}
nums
.left
and right
pointers traverse the array at most once, resulting in a linear pass through the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?