Skip to content

Commit 17e8cd9

Browse files
committed
feat: knapsack-dynamic-programming challenge
1 parent eacfb6b commit 17e8cd9

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def knapsack(weights, values, capacity):
2+
n = len(weights)
3+
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
4+
5+
for i in range(1, n + 1):
6+
for w in range(capacity + 1):
7+
if weights[i-1] <= w:
8+
dp[i][w] = max(values[i-1] + dp[i-1][w - weights[i-1]], dp[i-1][w])
9+
else:
10+
dp[i][w] = dp[i-1][w]
11+
12+
return dp[n][capacity]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Challenge: Solve the 0/1 knapsack problem using dynamic programming.
2+
# Given a set of items with weights and values, determine the combination that maximizes value without exceeding the capacity.
3+
4+
from knapsack import knapsack
5+
6+
def main():
7+
weights = [2, 3, 4, 5]
8+
values = [3, 4, 5, 6]
9+
capacity = 5
10+
max_value = knapsack(weights, values, capacity)
11+
print(f"Maximum value in knapsack with capacity {capacity}: {max_value}")
12+
13+
if __name__ == "__main__":
14+
main()

0 commit comments

Comments
 (0)