Skip to content

Commit cd07f74

Browse files
committed
added Unbounded Knapsack
1 parent 0a08a0f commit cd07f74

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Unbounded Knapsack
2+
3+
## Problem:
4+
5+
Given `weights`: list of weights where `weights[i]` represents the weight of `i-th` item,
6+
`values` : list of values where `values[i]` represents the value of `i-th` item,
7+
and `capacity`, total capacity available,
8+
Find the maximum values that can be achieved within the limit of total weight.
9+
10+
**same items can be used multiple times**
11+
12+
## Example:
13+
14+
```
15+
weights = [1,2,3,5]
16+
values = [1,4,7,10]
17+
capacity = 8
18+
Output: 18
19+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def unboundedKnapsack(weights, values, capacity):
2+
dp = [[0 for _ in range(capacity+1)] for _ in range(len(weights)+1)]
3+
for i in range(1, len(dp)):
4+
for j in range(1, len(dp[i])):
5+
if weights[i-1] <= j:
6+
dp[i][j] = max(dp[i-1][j], dp[i][j-weights[i-1]]+values[i-1])
7+
else:
8+
dp[i][j] = dp[i-1][j]
9+
# print(dp)
10+
return dp[-1][-1]
11+
12+
13+
weights = [1, 2, 3, 5]
14+
values = [1, 4, 7, 10]
15+
capacity = 8
16+
print(unboundedKnapsack(weights, values, capacity))

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ Languages used: Java and Python
6868
- [Predict Winner](DynamicProgramming/PredictWinner)
6969
- [Reducing Dishes](DynamicProgramming/ReducingDishes)
7070
- [Regex Matching](DynamicProgramming/RegexMatching)
71+
- [Unbounded Knapsack](DynamicProgramming/UnboundedKnapsack)
7172
- [Unique Paths](DynamicProgramming/UniquePaths)
73+
- [0-1 Knapsack](DynamicProgramming/ZeroOneKnapsack)
7274

7375
### [Graph](./Graph)
7476

0 commit comments

Comments
 (0)