(cap: int, weights: List[int], values: List[int])
| 2 | |
| 3 | |
| 4 | def knapsack(cap: int, weights: List[int], values: List[int]) -> int: |
| 5 | n = len(values) |
| 6 | # Base case: Set the first column and last row to 0 by |
| 7 | # initializing the entire DP table to 0. |
| 8 | dp = [[0 for x in range(cap + 1)] for x in range(n + 1)] |
| 9 | # Populate the DP table. |
| 10 | for i in range(n - 1, -1, -1): |
| 11 | for c in range(1, cap + 1): |
| 12 | # If the item 'i' fits in the current knapsack capacity, |
| 13 | # the maximum value at 'dp[i][c]' is the largest of either: |
| 14 | # 1. The maximum value if we include item 'i'. |
| 15 | # 2. The maximum value if we exclude item 'i'. |
| 16 | if weights[i] <= c: |
| 17 | dp[i][c] = max(values[i] + dp[i + 1][c - weights[i]], dp[i + 1][c]) |
| 18 | # If it doesn't fit, we have to exclude it. |
| 19 | else: |
| 20 | dp[i][c] = dp[i + 1][c] |
| 21 | return dp[0][cap] |
nothing calls this directly
no outgoing calls
no test coverage detected