题解 | 小红的整数配对

小红的整数配对

https://www.nowcoder.com/practice/66b9810e4fe34956a8d1f5c67aacc6dc

贪心

注意数字范围,使用long。题目范围没给清楚

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();
        long k=in.nextLong();
        long[] a=new long[n];
        for(int i=0;i<n;i++){
            a[i]=in.nextLong();
        }
        Arrays.sort(a);
        long res=0;
        for(int i=n-1;i>0;){
            if(a[i]-a[i-1]<=k){
                res+=a[i]*a[i-1];
                i-=2;

            }else{
                i--;
            }
        }
        System.out.println(res);


    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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