题解 | #相差不超过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);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        long target = in.nextLong();

        long[] arr = new long[n];

        for (int i = 0; i < n; i++) {
            arr[i] = in.nextLong();
        }

        Arrays.sort(arr);

        int res = 0;

        int l = 0;
        int r = 0;

        //因为要遍历到最后一个所以条件r<n
        while (r < n) {
            if (arr[r] - arr[l] > target) {
                l++;
            }
            //能够取值肯定在两棵指针之间,所以res的计算方法如下
            res = Math.max(res, r - l + 1);
            r++;
        }

        System.out.println(res);
    }
}

全部评论

相关推荐

谁知道呢_:要掉小珍珠了,库库学三年,这个结果
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务