Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimise search

Given multiple options, I need to select n of them, such that the total rating is maximized, but the total cost does not exceed the budget.

var options = [
    { rating: 8, cost: 6, },
    { rating: 5, cost: 4, },
    //...100 of these in total
];

function select(n, budget) {
    //TODO: Replace this code with some real implementation
    return options.slice(0, 5);
}

//Sudocode:
var result = select(5, 25);
Assert(result.length == 5);
Assert(sum(result.cost) <= 25);
Assert(sum(result.rating) is maximized);

I have tried a few different options, all variations of loops inside loops. But of course, they perform very slowly or never return at all.

I think that just looping is never going to work, and that there must be a fundamentally different approach to this problem.

like image 537
Swesus Avatar asked Nov 28 '25 17:11

Swesus


1 Answers

This is exactly the knapsack problem, which is NP-Complete - so there is no known polynomial solution to it.

However, if your weights (costs) are relatively small integers, there is a pretty efficient pseudo-polynomial solution using dynamic programming.

like image 173
amit Avatar answered Dec 01 '25 06:12

amit