题解 | #相差不超过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);
    }
}

全部评论

相关推荐

05-26 16:13
门头沟学院 C++
牢大肘击Java:海投就完事了bro,就当刷视频了
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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