0% found this document useful (0 votes)
3 views

report algo

Uploaded by

jumana.elashry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

report algo

Uploaded by

jumana.elashry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

KNAPSACK WITH DYNAMIC

PROGRAMMING

HANA AHMED EBRHAIM


1210120
Repetition Knapsack with Dynamic Programming
Main Idea
The Repetition Knapsack Problem allows unlimited copies of each item to be
included in the knapsack.
To solve this problem using Dynamic Programming, we build a table to store the
maximum value attainable for
every capacity from 0 to W. The key idea is to compute the solution iteratively,
considering each item and
the possibility of including it multiple times.

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]

- For Item 2 (Weight = 3, Value = 40):


dp[j] = max(dp[j], dp[j - 3] + 40) for j = 3 to 5.
Result: dp = [0, 10, 20, 40, 50, 60]

- For Item 3 (Weight = 4, Value = 50):


dp[j] = max(dp[j], dp[j - 4] + 50) for j = 4 to 5.
Final Result: dp = [0, 10, 20, 40, 50, 60]

3. Final Answer: The maximum value that can fit into the knapsack of capacity W = 5
is 60.

You might also like