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

Function knapsack

kotlin/Dynamic Programming/Knapsack.kt:1–22  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1fun knapsack(cap: Int, weights: List<Int>, values: List<Int>): Int {
2 val n = values.size
3 // Base case: Set the first column and last row to 0 by
4 // initializing the entire DP table to 0.
5 val dp = Array(n + 1) { IntArray(cap + 1) }
6 // Populate the DP table.
7 for (i in n - 1 downTo 0) {
8 for (c in 1..cap) {
9 // If the item 'i' fits in the current knapsack capacity,
10 // the maximum value at 'dp[i][c]' is the largest of either:
11 // 1. The maximum value if we include item 'i'.
12 // 2. The maximum value if we exclude item 'i'.
13 if (weights[i] <= c) {
14 dp[i][c] = Math.max(values[i] + dp[i + 1][c - weights[i]], dp[i + 1][c])
15 } else {
16 // If it doesn't fit, we have to exclude it.
17 dp[i][c] = dp[i + 1][c]
18 }
19 }
20 }
21 return dp[0][cap]
22}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected