I\'m doing a Knapsack in Java where we only use weights no value. The weightlimit is 1000. We get 5 weights scanned from keyboard which we use. The twist is that you can ac
The classical knapsack problem is discussed in a Wikipedia article; the dynamic programming formulation for the classical problem can be adapted to the following problem.
Given weights w_1,...,w_n and a target capacity W, find a subset of the items for which the total weight is minimal, but larger than W.
To avoid pathological cases, we assume that the sum of the weights is largert than W, otherwise there is no solution. Let W_MAX denote the sum of all weights.
For the dynamic programming formulation, let
m[i,j] for each i in 0,...,n and j in 0,...,W_MAX
denote the minimum weight larger than W attainable by discarding weights from 0,...,i with total weight exactly j.
We obtain
m[0,j] = W_MAX for each j in 0,...n
and get the recurrence relation
m[i,j] = min {
m[i-1, i ], // corresponds to keeping weight i
m[i-1, j - w[i]] - w[i] // corresponds to discarding weight i
}
and evaluation can be implemented by iterating i=0,...,n and j=0,...,W_MAX; accedd to m outside of these bounds must be assumed to yield W_MAX. Similar to the classical knapsack problem, the actual set of items to discard can be found by backtracking.
Finally, the given instance can be optimized twice; first with the algorithm above, then with the classical knapsack algorithm.