ztv
ztv

Reputation: 134

Knapsack but exact weight

Is there a algorithm to determine a knapsack which has an exact weight W? I.e. it's like the normal 0/1 knapsack problem with n items each having weight w_i and value v_i. Maximise the value of all the items, however the total weight of the items in the knapsack need to have exactly weight W!

I know the "normal" 0/1 knapsack algorithm but this could also return a knapsack with less weight but higher value. I want to find the highest value but exact W weight.

Here is my 0/1 knapsack implementation:

public class KnapSackTest {
    public static void main(String[] args) {
        int[] w = new int[] {4, 1, 5, 8, 3, 9, 2};  //weights
        int[] v = new int[] {2, 12, 8, 9, 3, 4, 3}; //values

        int n = w.length;
        int W = 15; // W (max weight)

        int[][] DP = new int[n+1][W+1];

        for(int i = 1; i < n+1; i++) {
            for(int j = 0; j < W+1; j++) {
                if(i == 0 || j == 0) {
                    DP[i][j] = 0;
                } else if (j - w[i-1] >= 0) {
                    DP[i][j] = Math.max(DP[i-1][j], DP[i-1][j - w[i-1]] + v[i-1]);
                } else {
                    DP[i][j] = DP[i-1][j];
                }
            }
        }
        System.out.println("Result: " + DP[n][W]);
    }
}

This gives me:

Result: 29

(Just ask if anything is unclear in my question!)

Upvotes: 5

Views: 4797

Answers (2)

Michal Rus
Michal Rus

Reputation: 1848

Actually, the accepted answer is wrong, as found by @Shinchan in the comments.

You get exact weight knapsack by changing only the initial dp state, not the algorithm itself.

The initialization, instead of:

            if(i == 0 || j == 0) {
                DP[i][j] = 0;
            }

should be:

            if (j == 0) {
                DP[i][j] = 0;
            } else if (i == 0 && j > 0) { // obviously `&& j > 0` is not needed, but for clarity
                DP[i][j] = -inf;
            }

The rest stays as in your question.

Upvotes: 5

amit
amit

Reputation: 178451

By simply setting DP[i][j] = -infinity in your last else clause it will do the trick.

The ides behind it is to slightly change the recursive formula definition to calculate:

  • Find the maximal value with exactly weight j up to item i.

Now, the induction hypothesis will change, and the proof of correctness will be very similar to regular knapsack with the following modification:

DP[i][j-weight[i]] is now the maximal value that can be constructed with exactly j-weight[i], and you can either take item i, giving value of DP[i][j-weight[i]], or not taking it, giving value of DP[i-1][j] - which is the maximal value when using exactly weight j with first i-1 items.

Note that if for some reason you cannot construct DP[i][j], you will never use it, as the value -infinity will always discarded when looking for MAX.

Upvotes: 2

Related Questions