Skip to content

Commit b3acac4

Browse files
Apply suggestions from code review
Co-authored-by: Oleksandr Kulkov <adamant.pwn@gmail.com>
1 parent 4b5361d commit b3acac4

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

src/dynamic_programming/knapsack.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,12 @@ From this we can derive the dp transition equation:
3434

3535
$$f_{i, j} = \max(f_{i-1, j}, f_{i-1, j-w_i} + v_i)$$
3636

37-
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
3838

3939
$$f_j \gets \max(f_j, f_{j-w_i}+v_i)$$
4040

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+
4143
**It is important to understand this transition rule, because most of the transitions for knapsack problems are derived in a similar way.**
4244

4345
### Implementation
@@ -50,7 +52,7 @@ for (int i = 1; i <= n; i++)
5052
f[j] = max(f[j], f[j - w[i]] + v[i]);
5153
```
5254

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.
5456

5557
## Complete Knapsack
5658

@@ -84,8 +86,8 @@ The alorithm described can be implemented in $O(nW)$ as:
8486

8587
```.c++
8688
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]);
8991
```
9092

9193
Despite having the same transition rule, the code above is incorrect for 0-1 knapsack.

0 commit comments

Comments
 (0)