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

全部评论

相关推荐

04-08 10:36
已编辑
华南理工大学 C++
点赞 评论 收藏
分享
ResourceUtilization:算法很难了,现在都需要相关论文还有对应的实习,可以先试试中厂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务