Skip to content

Commit dc242ad

Browse files
committed
Add Knapsack
1 parent 2efa03a commit dc242ad

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
fun 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+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
fun knapsackOptimized(cap: Int, weights: List<Int>, values: List<Int>): Int {
2+
val n = values.size
3+
// Initialize 'prevRow' as the DP values of the row below the
4+
// current row.
5+
var prevRow = IntArray(cap + 1)
6+
for (i in n - 1 downTo 0) {
7+
// Set the first cell of the 'currRow' to 0 to set the base
8+
// case for this row. This is done by initializing the entire
9+
// row to 0.
10+
val currRow = IntArray(cap + 1)
11+
for (c in 1..cap) {
12+
// If item 'i' fits in the current knapsack capacity, the
13+
// maximum value at 'currRow[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+
currRow[c] = Math.max(values[i] + prevRow[c - weights[i]], prevRow[c])
18+
} else {
19+
// If it doesn't fit, we have to exclude it.
20+
currRow[c] = prevRow[c]
21+
}
22+
}
23+
// Set 'prevRow' to 'currRow' values for the next iteration.
24+
prevRow = currRow
25+
}
26+
return prevRow[cap]
27+
}

0 commit comments

Comments
 (0)