算法 【贪心】BISHI48 小红的整数配对 思路 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); String[] str = br.readLine().split("\\s+"); int n = Integer.parseInt(str[0]); int k = Integer.parseInt(str[1]); String[] numStr = br.readLine().split("\\s+"); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(numStr[i]); } Arrays.sort(a); long maxScore = 0; int i = n - 1;// 从末尾开始遍历 // 从后往前贪心配对 while (i >= 1) { if (a[i] - a[i - 1] <= k) { maxScore += (long) a[i] * a[i - 1]; i -= 2;// 配对成功,跳过这两个元素 } else { i -= 1;// 无法配对,只跳过当前元素 } } out.println(maxScore); out.flush(); out.close(); br.close(); }