You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Further, as $f_{i}$ is only dependent on $f_{i-1}$, we can remove the first dimension. We obtain:
37
+
Further, as $f_{i}$ is only dependent on $f_{i-1}$, we can remove the first dimension. We obtain the transition rule
38
38
39
39
$$f_j \gets \max(f_j, f_{j-w_i}+v_i)$$
40
40
41
+
that should be executed in the **decreasing** order of $j$ (so that $f_{j-w_i}$ implicitly corresponds to $f_{i-1,j-w_i}$ and not $f_{i,j-w_i}$).
42
+
41
43
**It is important to understand this transition rule, because most of the transitions for knapsack problems are derived in a similar way.**
42
44
43
45
### Implementation
@@ -50,7 +52,7 @@ for (int i = 1; i <= n; i++)
50
52
f[j] = max(f[j], f[j - w[i]] + v[i]);
51
53
```
52
54
53
-
Note the order of enumeration. We go over all possible weights for each item rather than the other way round. If we execute the loops in the other order, $f_W$ will get updated assuming that we can pick only one item.
55
+
Again, note the order of execution. It should be strictly followed to ensure the following invariant: Right before the pair $(i, j)$ is processed, $f_k$ corresponds to $f_{i,k}$ for $k > j$, but to $f_{i-1,k}$ for $k < j$. This ensures that $f_{j-w_i}$ is taken from the $(i-1)$-th step, rather than from the $i$-th one.
54
56
55
57
## Complete Knapsack
56
58
@@ -84,8 +86,8 @@ The alorithm described can be implemented in $O(nW)$ as:
84
86
85
87
```.c++
86
88
for (int i = 1; i <= n; i++)
87
-
for (int j = 0; j <= W-w[i]; j++)
88
-
f[j + w[i]] = max(f[j + w[i]], f[j] + v[i]);
89
+
for (int j = w[i]; j <= W; j++)
90
+
f[j] = max(f[j], f[j - w[i]] + v[i]);
89
91
```
90
92
91
93
Despite having the same transition rule, the code above is incorrect for 0-1 knapsack.
0 commit comments