先将数组里面的每个数都减 ,然后找最长的和为 的连续段,我们用前缀和加速,设数组 为前缀和数组,对于每个 我们只需要找到 数组最靠前的值为 的位置即可,这个用 存一下即可。
#include<bits/stdc++.h>
#define int long long
#define double long double
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 3e5 + 10;
const int M = 1e3 + 10;
int mod = 1e9 + 7;
int a[N];
void solve() {
int n, k;
cin >> n >> k;
map<int, int>mp;
mp[0] = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
a[i] -= k;
a[i] += a[i - 1];
if (mp.count(a[i])) continue;
mp[a[i]] = i;
}
// for(int i=1;i<=n;i++) cout<<a[i]<<" ";
// cout<<"\n";
int maxx = -1;
for (int i = 1; i <= n; i++) {
if (mp.count(a[i]) && mp[a[i]] < i) maxx = max(maxx, i - mp[a[i]]);
}
cout << maxx << "\n";
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int _;
_ = 1;
//cin>>_;
while (_--) {
solve();
}
}