-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0862.cpp
More file actions
35 lines (27 loc) · 939 Bytes
/
0862.cpp
File metadata and controls
35 lines (27 loc) · 939 Bytes
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
29
30
31
32
33
34
35
class Solution {
public:
int shortestSubarray(vector<int> &nums, int targetSum) {
int n = nums.size();
vector<long long> prefixSums(n + 1, 0);
for (int i = 1; i <= n; i++) {
prefixSums[i] = prefixSums[i - 1] + nums[i - 1];
}
deque<int> candidateIndices;
int shortestSubarrayLength = INT_MAX;
for (int i = 0; i <= n; i++) {
while (!candidateIndices.empty() &&
prefixSums[i] - prefixSums[candidateIndices.front()] >=
targetSum) {
shortestSubarrayLength =
min(shortestSubarrayLength, i - candidateIndices.front());
candidateIndices.pop_front();
}
while (!candidateIndices.empty() &&
prefixSums[i] <= prefixSums[candidateIndices.back()]) {
candidateIndices.pop_back();
}
candidateIndices.push_back(i);
}
return shortestSubarrayLength == INT_MAX ? -1 : shortestSubarrayLength;
}
};