I need to get the best combination of numbers from the array numbers
that are closest to the number max
.
(addition numbers from array numbers
is allowed)
var numbers = [2, 5, 3, 7, 9, 20, 54, 89, 10]; // some numbers in array
var max = 10; // the highest possible number we want to get from array
var highest = [];
In this case, the output should be (3, 7) or (2, 5, 3) or (10), the output should not be 9
I have done this, but this is not what I want.
var possibles = numbers.filter(number => number <= max);
highest.push(Math.max(...possibles));
possibles.sort((a,b) => b - a);
possibles.forEach(number =>{
if( (max - highest[0]) <= number){
highest.push(Math.max(...possibles));
}
});
The output in this case is 9, which is not the highest possible number.