Skip to content

Commit afd80e5

Browse files
author
Partho Biswas
committed
algoexpert.io - Knapsack_Problem
1 parent b0de3ca commit afd80e5

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ A place where I upload my daily practice on Data Structure and Algorithm problem
143143
|45| [Max_Sum_Increasing_Subsequence](algoexpert.io/questions/Max_Sum_Increasing_Subsequence.md) | [Python](algoexpert.io/python/Max_Sum_Increasing_Subsequence.py) |
144144
|46| [Longest_Common_Subsequence](algoexpert.io/questions/Longest_Common_Subsequence.md) | [Python](algoexpert.io/python/Longest_Common_Subsequence.py) |
145145
|47| [Water_Area](algoexpert.io/questions/Water_Area.md) | [Python](algoexpert.io/python/Water_Area.py) |
146+
|48| [Knapsack_Problem](algoexpert.io/questions/Knapsack_Problem.md) | [Python](algoexpert.io/python/Knapsack_Problem.py) |
146147

147148

148149

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
3+
# O(N*Capacity) time | # O(N*Capacity) space
4+
def knapSackProblem(items, capacity):
5+
knapSackValues = [[0 for x in range(0, capacity) + 1] for y in range(0, len(items) + 1)]
6+
for i in range(1, len(items) + 1):
7+
currentWeight = items[i - 1][1]
8+
currentValue = items[i - 1][0]
9+
for individualCapacity in range(0, capacity + 1):
10+
if currentWeight > capacity:
11+
knapSackValues[i][individualCapacity] = knapSackValues[i - 1][individualCapacity]
12+
else:
13+
knapSackValues[i][individualCapacity] = max(knapSackValues[i - 1][individualCapacity], knapSackValues[i - 1][individualCapacity - currentWeight] + currentValue)
14+
return [knapSackValues[-1][-1], getKnapsackItems(knapSackValues, items)]
15+
16+
17+
def getKnapsackItems(knapSackValues, items):
18+
sequence = []
19+
i = len(knapSackValues) - 1
20+
individualCapacity = len(knapSackValues[0]) - 1
21+
while i > 0:
22+
if knapSackValues[i][individualCapacity] == knapSackValues[i - 1][individualCapacity]:
23+
i -= 1
24+
else:
25+
sequence.append(i - 1)
26+
individualCapacity -= items[i - 1][1]
27+
i -= 1
28+
if individualCapacity == 0:
29+
break
30+
return list(reversed(sequence))
31+
32+
33+
34+

0 commit comments

Comments
 (0)