给定长度为n的正整数数列以及正整数S,求出总和不小于S的连续子串的长度的最小值,如果解不存在,则输出
该题使用双指针,创建滑动窗口解决,注意sum的使用,不能暴力计算,否则会超时
//双指针滑动窗口
#include <iostream>
#include <algorithm>
typedef long long ll;
const int MAX_N = 1e5 + 5;
using namespace std;
void solve(){
ll n, s = 0;
ll a[MAX_N] = {0};
int r = 1;
cin >> n >> s;
int ans = n + 1;
for (int i = 1; i <= n; i++){
cin >> a[i];
}
ll sum = a[1];
for (int l = 1; l <= n; l++){
while(sum < s && r <= n){
r++;
sum += a[r];
}
if(sum >= s)
ans = min(ans, r - l + 1);
sum -= a[l];
}
if(ans != n + 1)
cout << ans << endl;
else
cout << 0 << endl;
}
int main(){
int N;
cin >> N;
for (int i = 0; i < N; i++){
solve();
}
return 0;
}