report algo
report algo
PROGRAMMING
For a knapsack with capacity W and n items, the recurrence relation is:
dp[j] = max(dp[j], dp[j - w[i]] + v[i])
Where:
- dp[j]: Maximum value attainable with knapsack capacity j.
- w[i]: Weight of the i-th item.
- v[i]: Value of the i-th item.
The algorithm iterates through all capacities j and all items, updating the dp[j] array
to ensure the optimal solution.
Steps:
1. Initialize a dp[] array of size W+1, with all elements set to 0.
2. For each item i, iterate through capacities j from w[i] to W.
3. Update dp[j] using the recurrence relation.
4. The value dp[W] will contain the maximum value attainable.
2D Example
Consider the following problem setup:
- Knapsack Capacity: W = 5
- Items:
1. Item 1: Weight = 1, Value = 10
2. Item 2: Weight = 3, Value = 40
3. Item 3: Weight = 4, Value = 50
We aim to maximize the total value that can fit into the knapsack.
Step-by-Step Solution:
1. Initialize a DP array: dp = [0, 0, 0, 0, 0, 0] (size W+1).
2. Iterate over each item and update the DP array:
- For Item 1 (Weight = 1, Value = 10):
dp[j] = max(dp[j], dp[j - 1] + 10) for j = 1 to 5.
Result: dp = [0, 10, 20, 30, 40, 50]
3. Final Answer: The maximum value that can fit into the knapsack of capacity W = 5
is 60.