MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / knapsack

Function knapsack

python3/Dynamic Programming/knapsack.py:4–21  ·  view source on GitHub ↗
(cap: int, weights: List[int], values: List[int])

Source from the content-addressed store, hash-verified

2
3
4def 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]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected