Translate all code to English (#1836)

* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
This commit is contained in:
Yudong Jin
2025-12-31 07:44:52 +08:00
committed by GitHub
parent 45e1295241
commit 2778a6f9c7
1284 changed files with 71557 additions and 3275 deletions
@@ -0,0 +1,45 @@
/**
* File: climbing_stairs_backtrack.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Backtracking */
fun backtrack(
choices: MutableList<Int>,
state: Int,
n: Int,
res: MutableList<Int>
) {
// When climbing to the n-th stair, add 1 to the solution count
if (state == n)
res[0] = res[0] + 1
// Traverse all choices
for (choice in choices) {
// Pruning: not allowed to go beyond the n-th stair
if (state + choice > n) continue
// Attempt: make choice, update state
backtrack(choices, state + choice, n, res)
// Backtrack
}
}
/* Climbing stairs: Backtracking */
fun climbingStairsBacktrack(n: Int): Int {
val choices = mutableListOf(1, 2) // Can choose to climb up 1 or 2 stairs
val state = 0 // Start climbing from the 0-th stair
val res = mutableListOf<Int>()
res.add(0) // Use res[0] to record the solution count
backtrack(choices, state, n, res)
return res[0]
}
/* Driver Code */
fun main() {
val n = 9
val res = climbingStairsBacktrack(n)
println("Climbing $n stairs has $res solutions")
}
@@ -0,0 +1,35 @@
/**
* File: climbing_stairs_constraint_dp.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Climbing stairs with constraint: Dynamic programming */
fun climbingStairsConstraintDP(n: Int): Int {
if (n == 1 || n == 2) {
return 1
}
// Initialize dp table, used to store solutions to subproblems
val dp = Array(n + 1) { IntArray(3) }
// Initial state: preset the solution to the smallest subproblem
dp[1][1] = 1
dp[1][2] = 0
dp[2][1] = 0
dp[2][2] = 1
// State transition: gradually solve larger subproblems from smaller ones
for (i in 3..n) {
dp[i][1] = dp[i - 1][2]
dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
}
return dp[n][1] + dp[n][2]
}
/* Driver Code */
fun main() {
val n = 9
val res = climbingStairsConstraintDP(n)
println("Climbing $n stairs has $res solutions")
}
@@ -0,0 +1,29 @@
/**
* File: climbing_stairs_dfs.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Search */
fun dfs(i: Int): Int {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2) return i
// dp[i] = dp[i-1] + dp[i-2]
val count = dfs(i - 1) + dfs(i - 2)
return count
}
/* Climbing stairs: Search */
fun climbingStairsDFS(n: Int): Int {
return dfs(n)
}
/* Driver Code */
fun main() {
val n = 9
val res = climbingStairsDFS(n)
println("Climbing $n stairs has $res solutions")
}
@@ -0,0 +1,36 @@
/**
* File: climbing_stairs_dfs_mem.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Memoization search */
fun dfs(i: Int, mem: IntArray): Int {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2) return i
// If record dp[i] exists, return it directly
if (mem[i] != -1) return mem[i]
// dp[i] = dp[i-1] + dp[i-2]
val count = dfs(i - 1, mem) + dfs(i - 2, mem)
// Record dp[i]
mem[i] = count
return count
}
/* Climbing stairs: Memoization search */
fun climbingStairsDFSMem(n: Int): Int {
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
val mem = IntArray(n + 1)
mem.fill(-1)
return dfs(n, mem)
}
/* Driver Code */
fun main() {
val n = 9
val res = climbingStairsDFSMem(n)
println("Climbing $n stairs has $res solutions")
}
@@ -0,0 +1,46 @@
/**
* File: climbing_stairs_dp.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Climbing stairs: Dynamic programming */
fun climbingStairsDP(n: Int): Int {
if (n == 1 || n == 2) return n
// Initialize dp table, used to store solutions to subproblems
val dp = IntArray(n + 1)
// Initial state: preset the solution to the smallest subproblem
dp[1] = 1
dp[2] = 2
// State transition: gradually solve larger subproblems from smaller ones
for (i in 3..n) {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
/* Climbing stairs: Space-optimized dynamic programming */
fun climbingStairsDPComp(n: Int): Int {
if (n == 1 || n == 2) return n
var a = 1
var b = 2
for (i in 3..n) {
val temp = b
b += a
a = temp
}
return b
}
/* Driver Code */
fun main() {
val n = 9
var res = climbingStairsDP(n)
println("Climbing $n stairs has $res solutions")
res = climbingStairsDPComp(n)
println("Climbing $n stairs has $res solutions")
}
@@ -0,0 +1,71 @@
/**
* File: coin_change.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.min
/* Coin change: Dynamic programming */
fun coinChangeDP(coins: IntArray, amt: Int): Int {
val n = coins.size
val MAX = amt + 1
// Initialize dp table
val dp = Array(n + 1) { IntArray(amt + 1) }
// State transition: first row and first column
for (a in 1..amt) {
dp[0][a] = MAX
}
// State transition: rest of the rows and columns
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If exceeds target amount, don't select coin i
dp[i][a] = dp[i - 1][a]
} else {
// The smaller value between not selecting and selecting coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
}
}
}
return if (dp[n][amt] != MAX) dp[n][amt] else -1
}
/* Coin change: Space-optimized dynamic programming */
fun coinChangeDPComp(coins: IntArray, amt: Int): Int {
val n = coins.size
val MAX = amt + 1
// Initialize dp table
val dp = IntArray(amt + 1)
dp.fill(MAX)
dp[0] = 0
// State transition
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If exceeds target amount, don't select coin i
dp[a] = dp[a]
} else {
// The smaller value between not selecting and selecting coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
}
}
}
return if (dp[amt] != MAX) dp[amt] else -1
}
/* Driver Code */
fun main() {
val coins = intArrayOf(1, 2, 5)
val amt = 4
// Dynamic programming
var res = coinChangeDP(coins, amt)
println("Minimum coins needed to make target amount is $res")
// Space-optimized dynamic programming
res = coinChangeDPComp(coins, amt)
println("Minimum coins needed to make target amount is $res")
}
@@ -0,0 +1,66 @@
/**
* File: coin_change_ii.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
/* Coin change II: Dynamic programming */
fun coinChangeIIDP(coins: IntArray, amt: Int): Int {
val n = coins.size
// Initialize dp table
val dp = Array(n + 1) { IntArray(amt + 1) }
// Initialize first column
for (i in 0..n) {
dp[i][0] = 1
}
// State transition
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If exceeds target amount, don't select coin i
dp[i][a] = dp[i - 1][a]
} else {
// Sum of the two options: not selecting and selecting coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
}
}
}
return dp[n][amt]
}
/* Coin change II: Space-optimized dynamic programming */
fun coinChangeIIDPComp(coins: IntArray, amt: Int): Int {
val n = coins.size
// Initialize dp table
val dp = IntArray(amt + 1)
dp[0] = 1
// State transition
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If exceeds target amount, don't select coin i
dp[a] = dp[a]
} else {
// Sum of the two options: not selecting and selecting coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
}
}
}
return dp[amt]
}
/* Driver Code */
fun main() {
val coins = intArrayOf(1, 2, 5)
val amt = 5
// Dynamic programming
var res = coinChangeIIDP(coins, amt)
println("Number of coin combinations to make target amount is $res")
// Space-optimized dynamic programming
res = coinChangeIIDPComp(coins, amt)
println("Number of coin combinations to make target amount is $res")
}
@@ -0,0 +1,143 @@
/**
* File: edit_distance.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.min
/* Edit distance: Brute-force search */
fun editDistanceDFS(
s: String,
t: String,
i: Int,
j: Int
): Int {
// If both s and t are empty, return 0
if (i == 0 && j == 0) return 0
// If s is empty, return length of t
if (i == 0) return j
// If t is empty, return length of s
if (j == 0) return i
// If two characters are equal, skip both characters
if (s[i - 1] == t[j - 1]) return editDistanceDFS(s, t, i - 1, j - 1)
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
val insert = editDistanceDFS(s, t, i, j - 1)
val delete = editDistanceDFS(s, t, i - 1, j)
val replace = editDistanceDFS(s, t, i - 1, j - 1)
// Return minimum edit steps
return min(min(insert, delete), replace) + 1
}
/* Edit distance: Memoization search */
fun editDistanceDFSMem(
s: String,
t: String,
mem: Array<IntArray>,
i: Int,
j: Int
): Int {
// If both s and t are empty, return 0
if (i == 0 && j == 0) return 0
// If s is empty, return length of t
if (i == 0) return j
// If t is empty, return length of s
if (j == 0) return i
// If there's a record, return it directly
if (mem[i][j] != -1) return mem[i][j]
// If two characters are equal, skip both characters
if (s[i - 1] == t[j - 1]) return editDistanceDFSMem(s, t, mem, i - 1, j - 1)
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
val insert = editDistanceDFSMem(s, t, mem, i, j - 1)
val delete = editDistanceDFSMem(s, t, mem, i - 1, j)
val replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1)
// Record and return minimum edit steps
mem[i][j] = min(min(insert, delete), replace) + 1
return mem[i][j]
}
/* Edit distance: Dynamic programming */
fun editDistanceDP(s: String, t: String): Int {
val n = s.length
val m = t.length
val dp = Array(n + 1) { IntArray(m + 1) }
// State transition: first row and first column
for (i in 1..n) {
dp[i][0] = i
}
for (j in 1..m) {
dp[0][j] = j
}
// State transition: rest of the rows and columns
for (i in 1..n) {
for (j in 1..m) {
if (s[i - 1] == t[j - 1]) {
// If two characters are equal, skip both characters
dp[i][j] = dp[i - 1][j - 1]
} else {
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
}
}
}
return dp[n][m]
}
/* Edit distance: Space-optimized dynamic programming */
fun editDistanceDPComp(s: String, t: String): Int {
val n = s.length
val m = t.length
val dp = IntArray(m + 1)
// State transition: first row
for (j in 1..m) {
dp[j] = j
}
// State transition: rest of the rows
for (i in 1..n) {
// State transition: first column
var leftup = dp[0] // Temporarily store dp[i-1, j-1]
dp[0] = i
// State transition: rest of the columns
for (j in 1..m) {
val temp = dp[j]
if (s[i - 1] == t[j - 1]) {
// If two characters are equal, skip both characters
dp[j] = leftup
} else {
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
}
leftup = temp // Update for next round's dp[i-1, j-1]
}
}
return dp[m]
}
/* Driver Code */
fun main() {
val s = "bag"
val t = "pack"
val n = s.length
val m = t.length
// Brute-force search
var res = editDistanceDFS(s, t, n, m)
println("Changing $s to $t requires minimum $res edits")
// Memoization search
val mem = Array(n + 1) { IntArray(m + 1) }
for (row in mem)
row.fill(-1)
res = editDistanceDFSMem(s, t, mem, n, m)
println("Changing $s to $t requires minimum $res edits")
// Dynamic programming
res = editDistanceDP(s, t)
println("Changing $s to $t requires minimum $res edits")
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t)
println("Changing $s to $t requires minimum $res edits")
}
@@ -0,0 +1,125 @@
/**
* File: knapsack.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.max
/* 0-1 knapsack: Brute-force search */
fun knapsackDFS(
wgt: IntArray,
_val: IntArray,
i: Int,
c: Int
): Int {
// If all items have been selected or knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0
}
// If exceeds knapsack capacity, can only choose not to put it in
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, _val, i - 1, c)
}
// Calculate the maximum value of not putting in and putting in item i
val no = knapsackDFS(wgt, _val, i - 1, c)
val yes = knapsackDFS(wgt, _val, i - 1, c - wgt[i - 1]) + _val[i - 1]
// Return the larger value of the two options
return max(no, yes)
}
/* 0-1 knapsack: Memoization search */
fun knapsackDFSMem(
wgt: IntArray,
_val: IntArray,
mem: Array<IntArray>,
i: Int,
c: Int
): Int {
// If all items have been selected or knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0
}
// If there's a record, return it directly
if (mem[i][c] != -1) {
return mem[i][c]
}
// If exceeds knapsack capacity, can only choose not to put it in
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, _val, mem, i - 1, c)
}
// Calculate the maximum value of not putting in and putting in item i
val no = knapsackDFSMem(wgt, _val, mem, i - 1, c)
val yes = knapsackDFSMem(wgt, _val, mem, i - 1, c - wgt[i - 1]) + _val[i - 1]
// Record and return the larger value of the two options
mem[i][c] = max(no, yes)
return mem[i][c]
}
/* 0-1 knapsack: Dynamic programming */
fun knapsackDP(wgt: IntArray, _val: IntArray, cap: Int): Int {
val n = wgt.size
// Initialize dp table
val dp = Array(n + 1) { IntArray(cap + 1) }
// State transition
for (i in 1..n) {
for (c in 1..cap) {
if (wgt[i - 1] > c) {
// If exceeds knapsack capacity, don't select item i
dp[i][c] = dp[i - 1][c]
} else {
// The larger value between not selecting and selecting item i
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[n][cap]
}
/* 0-1 knapsack: Space-optimized dynamic programming */
fun knapsackDPComp(wgt: IntArray, _val: IntArray, cap: Int): Int {
val n = wgt.size
// Initialize dp table
val dp = IntArray(cap + 1)
// State transition
for (i in 1..n) {
// Traverse in reverse order
for (c in cap downTo 1) {
if (wgt[i - 1] <= c) {
// The larger value between not selecting and selecting item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[cap]
}
/* Driver Code */
fun main() {
val wgt = intArrayOf(10, 20, 30, 40, 50)
val _val = intArrayOf(50, 120, 150, 210, 240)
val cap = 50
val n = wgt.size
// Brute-force search
var res = knapsackDFS(wgt, _val, n, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
// Memoization search
val mem = Array(n + 1) { IntArray(cap + 1) }
for (row in mem) {
row.fill(-1)
}
res = knapsackDFSMem(wgt, _val, mem, n, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
// Dynamic programming
res = knapsackDP(wgt, _val, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
// Space-optimized dynamic programming
res = knapsackDPComp(wgt, _val, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
}
@@ -0,0 +1,51 @@
/**
* File: min_cost_climbing_stairs_dp.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.min
/* Minimum cost climbing stairs: Dynamic programming */
fun minCostClimbingStairsDP(cost: IntArray): Int {
val n = cost.size - 1
if (n == 1 || n == 2) return cost[n]
// Initialize dp table, used to store solutions to subproblems
val dp = IntArray(n + 1)
// Initial state: preset the solution to the smallest subproblem
dp[1] = cost[1]
dp[2] = cost[2]
// State transition: gradually solve larger subproblems from smaller ones
for (i in 3..n) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
}
return dp[n]
}
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
fun minCostClimbingStairsDPComp(cost: IntArray): Int {
val n = cost.size - 1
if (n == 1 || n == 2) return cost[n]
var a = cost[1]
var b = cost[2]
for (i in 3..n) {
val tmp = b
b = min(a, tmp) + cost[i]
a = tmp
}
return b
}
/* Driver Code */
fun main() {
val cost = intArrayOf(0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1)
println("Input stair cost list is ${cost.contentToString()}")
var res = minCostClimbingStairsDP(cost)
println("Minimum cost to climb stairs is $res")
res = minCostClimbingStairsDPComp(cost)
println("Minimum cost to climb stairs is $res")
}
@@ -0,0 +1,132 @@
/**
* File: min_path_sum.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.min
/* Minimum path sum: Brute-force search */
fun minPathSumDFS(grid: Array<IntArray>, i: Int, j: Int): Int {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0]
}
// If row or column index is out of bounds, return +∞ cost
if (i < 0 || j < 0) {
return Int.MAX_VALUE
}
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
val up = minPathSumDFS(grid, i - 1, j)
val left = minPathSumDFS(grid, i, j - 1)
// Return the minimum path cost from top-left to (i, j)
return min(left, up) + grid[i][j]
}
/* Minimum path sum: Memoization search */
fun minPathSumDFSMem(
grid: Array<IntArray>,
mem: Array<IntArray>,
i: Int,
j: Int
): Int {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0]
}
// If row or column index is out of bounds, return +∞ cost
if (i < 0 || j < 0) {
return Int.MAX_VALUE
}
// If there's a record, return it directly
if (mem[i][j] != -1) {
return mem[i][j]
}
// Minimum path cost for left and upper cells
val up = minPathSumDFSMem(grid, mem, i - 1, j)
val left = minPathSumDFSMem(grid, mem, i, j - 1)
// Record and return the minimum path cost from top-left to (i, j)
mem[i][j] = min(left, up) + grid[i][j]
return mem[i][j]
}
/* Minimum path sum: Dynamic programming */
fun minPathSumDP(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
// Initialize dp table
val dp = Array(n) { IntArray(m) }
dp[0][0] = grid[0][0]
// State transition: first row
for (j in 1..<m) {
dp[0][j] = dp[0][j - 1] + grid[0][j]
}
// State transition: first column
for (i in 1..<n) {
dp[i][0] = dp[i - 1][0] + grid[i][0]
}
// State transition: rest of the rows and columns
for (i in 1..<n) {
for (j in 1..<m) {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
}
}
return dp[n - 1][m - 1]
}
/* Minimum path sum: Space-optimized dynamic programming */
fun minPathSumDPComp(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
// Initialize dp table
val dp = IntArray(m)
// State transition: first row
dp[0] = grid[0][0]
for (j in 1..<m) {
dp[j] = dp[j - 1] + grid[0][j]
}
// State transition: rest of the rows
for (i in 1..<n) {
// State transition: first column
dp[0] = dp[0] + grid[i][0]
// State transition: rest of the columns
for (j in 1..<m) {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
}
}
return dp[m - 1]
}
/* Driver Code */
fun main() {
val grid = arrayOf(
intArrayOf(1, 3, 1, 5),
intArrayOf(2, 2, 4, 2),
intArrayOf(5, 3, 2, 1),
intArrayOf(4, 3, 5, 2)
)
val n = grid.size
val m = grid[0].size
// Brute-force search
var res = minPathSumDFS(grid, n - 1, m - 1)
println("Minimum path sum from top-left to bottom-right is $res")
// Memoization search
val mem = Array(n) { IntArray(m) }
for (row in mem) {
row.fill(-1)
}
res = minPathSumDFSMem(grid, mem, n - 1, m - 1)
println("Minimum path sum from top-left to bottom-right is $res")
// Dynamic programming
res = minPathSumDP(grid)
println("Minimum path sum from top-left to bottom-right is $res")
// Space-optimized dynamic programming
res = minPathSumDPComp(grid)
println("Minimum path sum from top-left to bottom-right is $res")
}
@@ -0,0 +1,68 @@
/**
* File: unbounded_knapsack.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_dynamic_programming
import kotlin.math.max
/* Unbounded knapsack: Dynamic programming */
fun unboundedKnapsackDP(wgt: IntArray, _val: IntArray, cap: Int): Int {
val n = wgt.size
// Initialize dp table
val dp = Array(n + 1) { IntArray(cap + 1) }
// State transition
for (i in 1..n) {
for (c in 1..cap) {
if (wgt[i - 1] > c) {
// If exceeds knapsack capacity, don't select item i
dp[i][c] = dp[i - 1][c]
} else {
// The larger value between not selecting and selecting item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[n][cap]
}
/* Unbounded knapsack: Space-optimized dynamic programming */
fun unboundedKnapsackDPComp(
wgt: IntArray,
_val: IntArray,
cap: Int
): Int {
val n = wgt.size
// Initialize dp table
val dp = IntArray(cap + 1)
// State transition
for (i in 1..n) {
for (c in 1..cap) {
if (wgt[i - 1] > c) {
// If exceeds knapsack capacity, don't select item i
dp[c] = dp[c]
} else {
// The larger value between not selecting and selecting item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[cap]
}
/* Driver Code */
fun main() {
val wgt = intArrayOf(1, 2, 3)
val _val = intArrayOf(5, 11, 15)
val cap = 4
// Dynamic programming
var res = unboundedKnapsackDP(wgt, _val, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, _val, cap)
println("Maximum item value not exceeding knapsack capacity is $res")
}