This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with ``-1`` s filled up
(i, wt, val, j)
| 8 | |
| 9 | |
| 10 | def mf_knapsack(i, wt, val, j): |
| 11 | """ |
| 12 | This code involves the concept of memory functions. Here we solve the subproblems |
| 13 | which are needed unlike the below example |
| 14 | F is a 2D array with ``-1`` s filled up |
| 15 | """ |
| 16 | global f # a global dp table for knapsack |
| 17 | if f[i][j] < 0: |
| 18 | if j < wt[i - 1]: |
| 19 | val = mf_knapsack(i - 1, wt, val, j) |
| 20 | else: |
| 21 | val = max( |
| 22 | mf_knapsack(i - 1, wt, val, j), |
| 23 | mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], |
| 24 | ) |
| 25 | f[i][j] = val |
| 26 | return f[i][j] |
| 27 | |
| 28 | |
| 29 | def knapsack(w, wt, val, n): |