# [LeeCode 862. 和至少为 K 的最短子数组]单调栈

## 1. 题目链接

[LeeCode 862. 和至少为 K 的最短子数组]

## 3. 解题思路

1. $i\le x$$i\le x$
2. $pre\left[x\right]\ge pre\left[i-1\right]+K$$pre[x] \ge pre[i-1]+K$
3. $min\left\{x-l+1\right\}$$min\{x-l+1\}$

## 4. 参考代码

#ifdef __LOCAL_WONZY__
#include <bits/stdc++.h>
using namespace std;
#endif

class Solution {
public:
typedef long long ll;
static const int inf = 0x3f3f3f3f;
vector<long long> pre;
long long sum(int le, int ri) {
return le == 0 ? pre[ri] : pre[ri] - pre[le - 1];
}
int shortestSubarray(vector<int>& A, int K) {
int n = A.size();
pre = vector<long long>(n);
pre[0] = A[0];
for(int i = 1; i < n; ++i) pre[i] = pre[i - 1] + A[i];
vector<int> stk(n);
int sz = 0, len = inf;
for(int i = n - 1; i >= 0; --i) {
while(sz > 0 && pre[stk[sz - 1]] <= pre[i]) -- sz;
stk[sz ++] = i;
long long val = (i == 0 ? 0 : pre[i - 1]) + K;
int lb = 0, ub = sz - 1, md, j = inf;
while(lb <= ub) {
int md = (lb + ub) >> 1;
if(pre[stk[md]] >= val) j = stk[md], lb = md + 1;
else ub = md - 1;
}
len = min(len, j - i + 1);
}
return len == inf ? -1 : len;
}
};

#ifdef __LOCAL_WONZY__
int main() {
#ifdef __LOCAL_WONZY__
freopen("input-1.txt", "r", stdin);
#endif
vector<int> a = {77,19,35,10,-14};
Solution s;
cout << s.shortestSubarray(a, 19) << endl;;
return 0;
}
#endif