# 35. 最大N个数与最小N个数的和
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on('line', function(input) {
const inputArr = input.split(' ').map(Number);
const size = inputArr[0];
rl.on('line', (line) => {
const nums = line.split(' ').map(Number);
rl.on('line', (nLine) => {
const n = Number(nLine);
console.log(getN(size, nums, n));
})
})
})
function getN(size, nums, n) {
if (nums.length < n*2) {
return -1;
}
const distinctNums = [...new Set(nums)].sort((a, b) => a - b);
let left = 0;
let right = distinctNums.length - 1;
let sum = 0;
while(n > 0) {
sum += distinctNums[left] + distinctNums[right];
left++;
right--;
n--;
}
return sum;
}
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
35
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
35