题解 | 相差不超过k的最多数

相差不超过k的最多数

https://www.nowcoder.com/practice/562630ca90ac40ce89443c91060574c6

/*
对于某个指针需要根据某个条件不断的移动的话,不要用if,用while
*/
#include <iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n,k;cin>>n>>k;
    vector<int>nums;
    for(int i = 0; i < n; i++){
        int tmp;cin>>tmp;
        nums.push_back(tmp);
    }
    sort(nums.begin(),nums.end());
    int cnt_res = 0;
    int left = 0;
    for(int right = 0; right < n;right++){
        while(nums[right] - nums[left] > k){
            left++;
        }
        cnt_res = max(cnt_res,right - left + 1);
    }
    cout<<cnt_res<<'\n';
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

02-28 01:18
已编辑
南昌大学 后端工程师
后测速成辅导一两个月...:把开源经历放个人项目上边应该更好,就像大部分人都把实习经历放个人项目上边
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务