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

相差不超过k的最多数

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        in.nextLine();

        int nums[] = new int[n];
        for(int i = 0;i < n;i++){
            nums[i] = in.nextInt();
        }

        Arrays.sort(nums);

        // 快慢指针定义
        int slow = 0;
        int fast = 0;
        
        int res = 0;
        while(fast < n){
            if(nums[fast] - nums[slow] > k){
                res = Math.max(res,fast - slow);
                slow++;
                continue;
            }
            fast++;
        }
        res = Math.max(res,fast - slow);
       System.out.println(res);
    }
}

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务