题解 | 组队

组队

https://www.nowcoder.com/practice/60c417b02a3b49708dbb634956bb65fe

Java

排序+滑动窗口

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T=in.nextInt();
        while(T-->0){
            int n=in.nextInt();
            int k=in.nextInt();
            int[] a=new int[n];
            for(int i=0;i<n;i++){
                a[i]=in.nextInt();
            }
            int res=0;
            Arrays.sort(a);
            for(int l=0,r=0;l<n;l++){
                while(r<n&&a[r]-a[l]<=k){
                    r++;
                }
                res=Math.max(res,r-l);
            }
            System.out.println(res);
            

        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
03-12 14:52
已编辑
长沙学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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