diff --git a/contrib/ds-algorithms/dynamic-programming.md b/contrib/ds-algorithms/dynamic-programming.md index 43149f8..54c6fcb 100644 --- a/contrib/ds-algorithms/dynamic-programming.md +++ b/contrib/ds-algorithms/dynamic-programming.md @@ -84,8 +84,32 @@ Y = "GXTXAYB" print("Length of Longest Common Subsequence:", longest_common_subsequence(X, Y, len(X), len(Y))) ``` +## Longest Common Subsequence Code in Python (Bottom-Up Approach) + +```python + +def longestCommonSubsequence(X, Y, m, n): + L = [[None]*(n+1) for i in range(m+1)] + for i in range(m+1): + for j in range(n+1): + if i == 0 or j == 0: + L[i][j] = 0 + elif X[i-1] == Y[j-1]: + L[i][j] = L[i-1][j-1]+1 + else: + L[i][j] = max(L[i-1][j], L[i][j-1]) + return L[m][n] + + +S1 = "AGGTAB" +S2 = "GXTXAYB" +m = len(S1) +n = len(S2) +print("Length of LCS is", longestCommonSubsequence(S1, S2, m, n)) +``` + ## Complexity Analysis -- **Time Complexity**: O(m * n) for the top-down approach, where m and n are the lengths of the input sequences +- **Time Complexity**: O(m * n) for both approaches, where m and n are the lengths of the input sequences - **Space Complexity**: O(m * n) for the memoization table @@ -122,11 +146,105 @@ capacity = 50 n = len(weights) print("Maximum value that can be obtained:", knapsack(weights, values, capacity, n)) ``` +## 0-1 Knapsack Problem Code in Python (Bottom-up Approach) +```python +def knapSack(capacity, weights, values, n): + K = [[0 for x in range(capacity + 1)] for x in range(n + 1)] + for i in range(n + 1): + for w in range(capacity + 1): + if i == 0 or w == 0: + K[i][w] = 0 + elif weights[i-1] <= w: + K[i][w] = max(values[i-1] + + K[i-1][w-weights[i-1]], + K[i-1][w]) + else: + K[i][w] = K[i-1][w] + + return K[n][capacity] + +values = [60, 100, 120] +weights = [10, 20, 30] +capacity = 50 +n = len(weights) +print(knapSack(capacity, weights, values, n)) +``` ## Complexity Analysis -- **Time Complexity**: O(n * W) for the top-down approach, where n is the number of items and W is the capacity of the knapsack +- **Time Complexity**: O(n * W) for both approaches, where n is the number of items and W is the capacity of the knapsack - **Space Complexity**: O(n * W) for the memoization table