Https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/
First, reviewValueThe method is to record a prefix min value and then scan the sum array.
1. First, we don't need the maximum value here, because it's just enough K.
2. The shortest distance is required. Is the shortest length of the array.
The idea here is the same, but it is better to save a lot of Min values, that is, to use a queue to save the min value of the prefix without the min value.
That is, if the value of the sum array is:
... 60, 40... y .....
In the original queue, 60 can pop out, because it is replaced by 40, because the value of Y minus 40 must be greater than 60, and it is more likely to be greater than K, and the distance is shorter.
class Solution {public: int shortestSubarray(vector<int> A, int k) { int len = (int)A.size(); deque<int> que; vector<int> sum(len + 1, 0); for (int i = 0; i < len; ++i) { sum[i + 1] = sum[i] + A[i]; } int ans = len + 1; que.push_back(0); for (int i = 1; i <= len; ++i) { while (que.size() > 0 && sum[i] - sum[que.front()] >= k) { ans = min(ans, i - que.front()); que.pop_front(); } while (que.size() > 0 && sum[i] <= que.back()) { que.pop_back(); } que.push_back(i); } return ans == len + 1 ? -1 : ans; }} t;
Leetcode 862 shorest subarray with sum at least K