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

全部评论

相关推荐

09-23 17:42
门头沟学院 Java
兄弟们我绷不住了,小米要求10月份参加编程考试,20级以下(王腾好像21),正式和外包都得去,还要部门大排名,一巴掌给我抽象的回到大学
flex*1022:雷:我们想了很久,到底怎么样才能让用户满意,让工程师保持手感,经过长达180天的思考,我连夜睡服高管,决定发起内部考试,以编程为主
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
码农索隆:谁问你了 举报了 删了,求你了 我要哭了 我一点也不眼红 我要跳楼
点赞 评论 收藏
分享
我不行了,我真过不了第二关
码农索隆:嘿,哥们连界面都进去去,更别提玩了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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