Find a sum equal or greater than given target using only numbers from set

后端 未结 2 1693
独厮守ぢ
独厮守ぢ 2021-01-13 03:51

Example 1:

Shop selling beer, available packages are 6 and 10 units per package. Customer inputs 26 and algorithm replies 26, because 26 = 10 + 10 + 6.

Ex

相关标签:
2条回答
  • 2021-01-13 04:05

    You want to solve the integer programming problem min(ct) s.t. ct >= T, c >= 0 where T is your target weight, and c is a non-negative integer vector specifying how much of each package to purchase, and t is the vector specifying the weight of each package. You can either solve this with dynamic programming as pointed out by another answer, or, if your weights and target weight are too large then you can use general integer programming solvers, which have been highly optimized over the years to give good speed performance in practice.

    0 讨论(0)
  • 2021-01-13 04:15

    First let's reduce this problem to integers rather than real numbers, otherwise we won't get a fast optimal algorithm out of this. For example, let's multiply all numbers by 100 and then just round it to the next integer. So say we have item sizes x1, ..., xn and target size Y. We want to minimize the value

    k1 x1 + ... + kn xn - Y

    under the conditions

    (1) ki is a non-positive integer for all n ≥ i ≥ 1

    (2) k1 x1 + ... + kn xn - Y ≥ 0

    One simple algorithm for this would be to ask a series of questions like

    1. Can we achieve k1 x1 + ... + kn xn = Y + 0?
    2. Can we achieve k1 x1 + ... + kn xn = Y + 1?
    3. Can we achieve k1 x1 + ... + kn xn = Y + z?
    4. etc. with increasing z

    until we get the answer "Yes". All of these problems are instances of the Knapsack problem with the weights set equal to the values of the items. The good news is that we can solve all those at once, if we can establish an upper bound for z. It's easy to show that there is a solution with z ≤ Y, unless all the xi are larger than Y, in which case the solution is just to pick the smallest xi.

    So let's use the pseudopolynomial dynamic programming approach to solve Knapsack: Let f(i,j) be 1 iif we can reach total item size j with the first i items (x1, ..., xi). We have the recurrence

    f(0,0) = 1
    f(0,j) = 0   for all j > 0
    f(i,j) = f(i - 1, j) or f(i - 1, j - x_i) or f(i - 1, j - 2 * x_i) ...
    

    We can solve this DP array in O(n * Y) time and O(Y) space. The result will be the first j ≥ Y with f(n, j) = 1.

    There are a few technical details that are left as an exercise to the reader:

    • How to implement this in Java
    • How to reconstruct the solution if needed. This can be done in O(n) time using the DP array (but then we need O(n * Y) space to remember the whole thing).
    0 讨论(0)
提交回复
热议问题