Cover image for Interview Classic 150 Questions P209 Minimum Size Subarray Sum

Interview Classic 150 Questions P209 Minimum Size Subarray Sum


Timeline

timeline

2025-11-11

init

sliding window

Problem:

Sliding window:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <vector>
#include <climits>
#include <algorithm>
using std::vector;

class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size();
int left = 0;
int curr_sum = 0;
int res = INT_MAX;

for (int right = 0; right < n; ++right) {
curr_sum += nums[right];

// When the sum within the window >= target, try to shrink the left boundary
while (curr_sum >= target) {
res = std::min(res, right - left + 1); // Record the minimum length

curr_sum -= nums[left];
left++;
}
}

return (res == INT_MAX ? 0 : res);
}
};