Given an array of items, each of which has a value and cost, what’s the best algorithm determine the items required to reach a minimum value at the minimum cost? eg:
Item: Value -> Cost ------------------- A 20 -> 11 B 7 -> 5 C 1 -> 2 MinValue = 30 naive solution: A + B + C + C + C. Value: 30, Cost 22 best option: A + B + B. Value: 34, Cost 21
Note that the overall value:cost ratio at the end is irrelevant (A + A would give you the best value for money, but A + B + B is a cheaper option which hits the minimum value).
This is the knapsack problem. (That is, the decision version of this problem is the same as the decision version of the knapsack problem, although the optimization version of the knapsack problem is usually stated differently.) It is NP-hard (which means no algorithm is known that is polynomial in the ‘size’ — number of bits — in the input). But if your numbers are small (the largest ‘value’ in the input, say; the costs don’t matter), then there is a simple dynamic programming solution.
Let best[v] be the minimum cost to get a value of (exactly) v. Then you can calculate the values best[] for all v, by (initializing all best[v] to infinity and):
Then look at best[v] for values upto the minimum you want plus the largest value; the smallest of those will give you the cost.
If you want the actual items (and not just the minimum cost), you can either maintain some extra data, or just look through the array of best[]s and infer from it.