-2

Given n items with ci cost and vi value with target value X, return the number of items such that the cost is minimized while the total value of the items reaches the target X.

To me, this sounds like a variation of a knapsack problem. We want to minimize the cost while still picking enough items to reach the target X, whereas in knapsack we want to reach the highest value while staying under a weight limit. What would be the best way to approach this problem?

Nick
  • 49
  • 6

1 Answers1

0

The following is a brute-force approach that would quickly become infeasible for large(r) n. I interpreted "reaches" as is not smaller than; if instead is equal to is meant, simply replace > with ==.

import numpy as np
from itertools import combinations

n = 10
X = 20
# mock some data
c = np.random.randint(1, 10, n)
v = np.random.randint(1, 10, n)

def f(c, v, X):
    n = len(c)
    cv = list(zip(c, v))
    best_k, best_cost = np.NaN, np.Inf
    for k in range(1, n + 1):
        for candidate in combinations(cv, k):
            ck, vk = zip(*candidate)
            X_hat, cost = sum(vk), sum(ck)
            if cost < best_cost and X_hat > X:
                best_cost, best_k = cost, k
    return best_k


sol = f(c, v, X)
print(sol)
Michael Hodel
  • 2,845
  • 1
  • 5
  • 10
  • I appreciate the answer! Unfortunately, in my case n can become very large such that the brute force solution will not be acceptable up to a certain point. I am certain a recurrence can be derived and perhaps the solution is trivial, but I haven't gotten there yet. – Nick Aug 13 '22 at 02:29