32 lines
969 B
Python
32 lines
969 B
Python
# 0/1 Knapsack Problem using Dynamic Programming
|
|
|
|
def knapsack_01(values, weights, capacity):
|
|
n = len(values)
|
|
# Create DP table: (n+1) x (capacity+1)
|
|
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
|
|
|
|
# Build table bottom-up
|
|
for i in range(1, n + 1):
|
|
for w in range(1, capacity + 1):
|
|
if weights[i - 1] <= w:
|
|
# Option 1: include the item
|
|
include = values[i - 1] + dp[i - 1][w - weights[i - 1]]
|
|
# Option 2: exclude the item
|
|
exclude = dp[i - 1][w]
|
|
dp[i][w] = max(include, exclude)
|
|
else:
|
|
dp[i][w] = dp[i - 1][w]
|
|
|
|
# The last cell contains the maximum value
|
|
return dp[n][capacity]
|
|
|
|
|
|
# Example usage
|
|
if __name__ == "__main__":
|
|
values = [60, 100, 120]
|
|
weights = [10, 20, 30]
|
|
capacity = 50
|
|
|
|
max_value = knapsack_01(values, weights, capacity)
|
|
print("Maximum value in Knapsack =", max_value)
|