[LeetCode] Shortest Subarray with Sum at Least K

862. Shortest Subarray with Sum at Least K

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.

A subarray is a contiguous part of an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int shortestSubarray(vector<int>& nums, int k) {
deque<pair<long, int>> dq {{0, -1}};
int res = INT_MAX;
long sum = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];

while(!dq.empty() and dq[0].first <= sum - k)
res = min(res, i - dq[0].second), dq.pop_front();

while(!dq.empty() and dq.back().first >= sum)
dq.pop_back();

dq.push_back({sum, i});
}
return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/22/PS/LeetCode/shortest-subarray-with-sum-at-least-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.