题解 | 小红的整数配对

小红的整数配对

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

import java.util.Scanner;
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();
        Integer []a=new Integer[n];
        boolean []used=new boolean[n];
        for(int i=0;i<n;i++)a[i]=in.nextInt();
        Arrays.sort(a,(b,c)->c-b);
        long sum=0;
        for(int i=0;i<n-1;i++){
            if(Math.abs(a[i]-a[i+1])<=k&&!used[i]&&!used[i+1]){
                sum+=(long)a[i]*a[i+1];
                used[i]=true;
                used[i+1]=true;
                i++;
            }
        }
        System.out.println(sum);
    }
}

全部评论

相关推荐

03-31 00:39
门头沟学院 C++
牛客20485985...:抱抱😘,首先你还有春招,然后就算这时候没上岸也没关系,大部分人都是这样,毕业了再找也成,最后工作只是生活的一小部分,找到工作也不是一个必须的事情。不要气馁不要焦虑你只是陷入了短暂的低谷,你也一直有退路
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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