- tags: Sliding Window,LeetCode101
Key:
- sum is greater than or equal to
target
- Compute minimal must above slide left window, as decrease may cause sum less than target.
- See also 1695. Maximum Erasure Value
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0;
int sum = 0;
int minimal = INT_MAX;
for (auto right = 0; right < nums.size(); right++) {
sum += nums[right];
while (sum >= target) {
minimal = min(minimal, right - left + 1);
sum -= nums[left++];
}
}
return minimal == INT_MAX ? 0 : minimal;
}
};