题解 | #平均数为k的最长连续子数组#(前缀和)

平均数为k的最长连续子数组

https://www.nowcoder.com/practice/2e47f99735584ac5ba30d75ac14d6524

#include "bits/stdc++.h"

using namespace std;
#define int long long
#define endl "\n"
#define PII pair<int,int>
#define PIII pair<int,PII>
const int MOD = 1e9 + 7;
const int N = 3e5;

void slu() {
    int n, k;
    cin >> n >> k;
    vector<int> a(n + 1, 0);
    unordered_map<int, int> m;
    int res = 0;

    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        a[i] -= k;
        a[i] += a[i - 1];
        if (a[i] == 0) res = max(res, i);
        else if (m[a[i]]) {
            res = max(res, i - m[a[i]]);
        } else {
            m[a[i]] = i;
        }
    }
    if (!res)res = -1;
    cout << res;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T;
//    cin >> T;
    T = 1;
    while (T--)slu();

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-18 14:29
牛客604067584号:感觉算法卷的人少很多,毕竟只有一部分bg还不错的硕士才会考虑算法,虽然hc不如后端,但是竞争真的少很多。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务