Skip to content

Commit 23aedf8

Browse files
authored
Merge pull request keon#87 from karpinski/knapsack
Adding an implementation for the knapsack problem.
2 parents 72c1402 + bbc68d3 commit 23aedf8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Minimal and clean example implementations of data structures and algorithms in P
6060
- [climbing_stairs](dp/climbing_stairs.py)
6161
- [combination_sum](dp/combination_sum.py)
6262
- [house_robber](dp/house_robber.py)
63+
- [knapsack](dp/knapsack.py)
6364
- [longest_increasing](dp/longest_increasing.py)
6465
- [max_product_subarray](dp/max_product_subarray.py)
6566
- [max_subarray](dp/max_subarray.py)

dp/knapsack.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Given the capacity of the knapsack and items specified by weights and values,
3+
return the maximum summarized value of the items that can be fit in the
4+
knapsack.
5+
6+
Example:
7+
capacity = 5, items(value, weight) = [(60, 5), (50, 3), (70, 4), (30, 2)]
8+
result = 80 (items valued 50 and 30 can both be fit in the knapsack)
9+
10+
The time complexity is O(n * m) and the space complexity is O(m), where n is
11+
the total number of items and m is the knapsack's capacity.
12+
"""
13+
14+
15+
class Item(object):
16+
17+
def __init__(self, value, weight):
18+
self.value = value
19+
self.weight = weight
20+
21+
22+
def get_maximum_value(items, capacity):
23+
dp = [0] * (capacity + 1)
24+
for item in items:
25+
dp_tmp = [total_value for total_value in dp]
26+
for current_weight in range(capacity + 1):
27+
total_weight = current_weight + item.weight
28+
if total_weight <= capacity:
29+
dp_tmp[total_weight] = max(dp_tmp[total_weight],
30+
dp[current_weight] + item.value)
31+
dp = dp_tmp
32+
return max(dp)
33+
34+
35+
print(get_maximum_value([Item(60, 10), Item(100, 20), Item(120, 30)],
36+
50))
37+
print(get_maximum_value([Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2)],
38+
5))

0 commit comments

Comments
 (0)