Knapsack Problem Section 7.6
Problem Suppose we have n items U={u 1,..u n }, that we would like to insert into a knapsack of size C. Each item u i has a size s i and a value v i. A choose a subset of items S U such that
Dynamic Programming Solution For 1 j C & 1 I n, let V[i,j] be the optimal value obtained by filling a knapsack of size j with items taken from {u 1,..u i }. Also V[i,0]=0 and V[0,j]=0. Our Goal is to find V[n,C]
Recursive Formula
Algorithm: Knapsack Input: Knapsack of size C, items U={u 1,..u n }, with sizes s 1,.., s n, and values v 1,.., v n Output: For i 0 to n V[i,0] 0 end for For j 0 to C V[0,j] 0 end for for i 1 to n for j 1 to C V[i,j] = V[i-1,j] if s i j then V[i,j] =max{V[i,j], V[i-1,j- s i ] + v i } end for Return V[n,C]
Performance Analysis Time = (nC) Space = (nC) But can be modified to use only (C) space by storing two rows only.
How does it work? s s C n n v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 Copy the above red line here = max{ + v2, }
How does it work? s s C n n v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 Copy the above red line here = max{ + v2, }
How does it work? s s C n n v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 Copy the above red line here = max{ + v2, }
How does it work? s s C n n v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 Copy the above red line here = max{ + v2, }
How does it work? s s C n n v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 Copy the above red line here = max{ + v2, }