File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
kotlin/Dynamic Programming Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments