[LeetCode] Minimum Size Subarray Sum

209. Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int res = INT_MAX, n = nums.size();
vector<int> p{0};
for(int l = 0, r = 0; r < n; r++) {
p.push_back(p.back() + nums[r]);
while(l <= r and p[r+1] - p[l] >= target) {
res = min(res, r + 1 - l++);
}
}
return res == INT_MAX ? 0 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/minimum-size-subarray-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.