同时减去k后, 求最长连续子数组和为0的值即可

代码:


using namespace std;

typedef long long ll;
typedef pair<ll, ll>PII;
const int N = 2e5 + 10;
const int MOD = 998244353;
const int INF = 0X3F3F3F3F;
const int dx[] = {-1, 1, 0, 0, -1, -1, +1, +1};
const int dy[] = {0, 0, -1, 1, -1, +1, -1, +1};
const int M = 1e6 + 10;

int n, k;
//同时减去k之后求最长连续子数组和为0的值
int main()
{
	map<ll, ll>ma;
	ma[0] = 0;
	cin >> n >> k;
	ll s = 0;//记录前缀和
	ll res = -1;
	for(int i = 1; i <= n; i ++)
	{
		ll x;
		cin >> x;
		s += x - k;
		if(ma.count(s)) res = max(res, i - ma[s]);
		else ma[s] = i;
	}
	cout << res << endl;
}