![]() |
VOOZH | about |
Given a knapsack with a fixed capacity and a set of n items, where each item has an associated value val[i] and weight wt[i], determine the maximum profit that can be obtained by filling the knapsack. Each item can be selected an unlimited number of times.
Examples:
Input: capacity = 100, val[] = [1, 30], wt[] = [1, 50]
Output: 100
Explanation: There are many ways to fill knapsack.
Option 1: 2 instances of 50 unit weight item.
Option 2: 100 instances of 1 unit weight item.
Option 3: 1 instance of 50 unit weight item and 50 instances of 1 unit weight items.
We get maximum value with option 2.
Input: capacity = 8, val[] = [10, 40, 50, 70], wt[] = [1, 3, 4, 5]
Output : 110
Explanation: We get maximum value with one unit of weight 5 and one unit of weight 3.
Table of Content
The idea is to use recursion by breaking the larger problem into smaller subproblems. For each item, we have two choices - either we include the item in our knapsack or we exclude it.
If the item is included, its value is added to the total profit and the problem is solved again for the same item with the remaining capacity reduced by its weight. If the item is excluded, we move to the next item while keeping the remaining capacity unchanged.
This process continues recursively until all items are considered, and the maximum profit is determined by taking the better of the include and exclude choices at each step.
100
This approach improves the recursive solution by storing the results of already solved subproblems. A 2D DP table is used where each state represents the maximum profit achievable for a given index and remaining capacity. dp[i][j] stores the maximum profit that can be achieved starting from index i with a remaining capacity of j. Before computing the value for a given (i, j) state, the DP table is checked to avoid recomputation. This ensures that each subproblem is solved only once.
100
In this approach, a DP table is built iteratively from smaller capacities to larger ones. Each DP state represents the maximum profit achievable for a given item index and knapsack capacity. Here, dp[i][j] represents the maximum profit obtainable using the first i items with a knapsack capacity of j. The table is filled iteratively by considering whether to include the current item (possibly multiple times, as it is unbounded) or exclude it.
100
This approach further optimizes the tabulation method by reducing the space complexity. Since the current DP state depends only on previously computed capacities, a 1D array is sufficient. The DP array is updated for each capacity by considering inclusion of the current item multiple times where dp[j] represents the maximum profit achievable with a knapsack capacity of j.
100