Minimum Size Subarray Sum
Given an array of positive integers nums and a target target, return the minimal length of a contiguous subarray of which the sum is greater than or equal to target. If there is no such subarray, return 0.
Because all elements $nums[i] \ge 0$, expanding $right$ monotonically increases window sum. When $sum \ge target$, contracting $left$ monotonically decreases sum. Thus, both $left$ and $right$ advance at most $N$ times, proving optimal $\mathcal{O}(N)$ time complexity and avoiding the naive $\mathcal{O}(N^2)$ brute force.
Sliding window counters are deployed in Envoy proxies protecting upstream microservices. By tracking rolling window increments in high-throughput distributed memory (Redis cluster with Lua scripts), requests exceeding quota within window $W$ are throttled with HTTP 429 in sub-millisecond latency without lock contention.
currentSum and minLen = Infinity.
Outer loop advances right from 0 to N-1.
Inner loop runs while (currentSum >= target):
update minLen = Math.min(minLen, right - left + 1), subtract nums[left++].
function maxSubarraySum(target, nums) {
let minLen = Infinity, sum = 0, left = 0;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
minLen = Math.min(minLen, right - left + 1);
sum -= nums[left++];
}
}
return minLen === Infinity ? 0 : minLen;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15