Added all DAA in python

This commit is contained in:
bhakti-thakur
2025-11-05 18:07:57 +05:30
parent c736aa00e3
commit 4b11369278
5 changed files with 278 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
# 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)