Setting
- We are given items
- Each item has a non-negative internal weight given by
- A number is given as an upper bound
The
Given a set of items with weights respectively and a bound , find a set of items such that is maximised subject to the constraint .
Attempting to design a DP algorithm
- Let denote the max weight of choosing items from such that the sum of weights is maximised subject to being at most .
- Final answer would be
- If item is not chosen in this set, then
- But if item is chosen in this set, then contains plus optimal way to choose items from with weight at most
- We are not remembering this in
- only stores max weight of choosing items from subject to weight being at most .
- So one variable is not enough: we need to store a table
- For each and ,
- let be the max weight of choosing items from subject to weight being at most .
Obtaining the recurrence
Let be the max weight of choosing items from subject to weight being at most
- If is not chosen, then we have
- This is enforced if
- If is chosen, the wen have
Hence, we obtain the following recurrence
Algorithm
Correctness
- Proof by induction on
- Base case is
- Inductive step is essentially argues the correctness of the recurrence from line 5
Running time
- The table has entries
- Filling up a new entry in the table needs to look-up two existing entries from the table, and do one addition & one max operation
- This needs constant time
- Hence, time required to fill up all entries is