题解 | 小红的整数配对
小红的整数配对
https://www.nowcoder.com/practice/66b9810e4fe34956a8d1f5c67aacc6dc
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 读取 n 和 k
if(!in.hasNextInt()) return;
int n = in.nextInt();
long k = in.nextLong();
long[] a = new long[n];
for(int i = 0; i < n; i++) {
a[i] = in.nextLong();
}
// 1.排序:从小到大
Arrays.sort(a);
long totalScore = 0;
// 2.贪心匹配:从大到小尝试匹配相邻的数
// 为什么从大到小?因为大数相乘对总分的贡献最大
for(int i = n - 1; i >= 1;) {
if(a[i] - a[i - 1] <= k) {
// 满足条件,匹配成功
totalScore += a[i] * a[i - 1];
// 移除这两个数,指针向前移2步
i -= 2;
} else {
// 当前最大的数无法与第二大的数配对,往前移1步
i--;
}
}
System.out.println(totalScore);
}
}