const solution = (k, arr) => {
const hash = {};
(function recursive(sliced, sum) {
console.log(sliced, sum);
if (sum.length == k) {
const total = sum.reduce((a, b) => a + b);
if (!hash.hasOwnProperty(total)) hash[total] = true;
return;
}
for (let i = 0; i < sliced.length; i++) {
const copiedSum = sum.concat(sliced[i]);
recursive(sliced.slice(i + 1), copiedSum);
}
})(arr, []);
return Object.keys(hash).sort((a, b) => b - a)[k - 1];
};
const result = solution(3, [13, 15, 34, 23, 45, 65, 33, 11, 26, 42]);
console.log(result);
const solution = (k, arr) => {
const set = new Set();
(function recursive(sliced, sum) {
if (sum.length == k) return set.add(sum.reduce((a, b) => a + b));
for (let i = 0; i < sliced.length; i++) {
const copiedSum = sum.concat(sliced[i]);
recursive(sliced.slice(i + 1), copiedSum);
}
})(arr, []);
return Array.from(set).sort((a, b) => b - a)[k - 1];
};
const result = solution(3, [13, 15, 34, 23, 45, 65, 33, 11, 26, 42]);
console.log(result);