|
| 1 | +/* |
| 2 | +Use this technique to select elements that give maximum profit from a given set with a limitation on capacity |
| 3 | +and that each element can be picked multiple times. |
| 4 | +*/ |
| 5 | + |
| 6 | +//1. Rod Cutting |
| 7 | +fun maxRodCuttingProfit(lengths: IntArray, prices: IntArray, rodLength: Int): Int { |
| 8 | + val n = lengths.size |
| 9 | + |
| 10 | + // Create a 1D array to store the maximum profit for each length |
| 11 | + val dp = IntArray(rodLength + 1) |
| 12 | + |
| 13 | + // Populate the array using the Unbounded Knapsack approach |
| 14 | + for (i in 1..rodLength) { |
| 15 | + for (j in 0 until n) { |
| 16 | + if (lengths[j] <= i) { |
| 17 | + dp[i] = maxOf(dp[i], dp[i - lengths[j]] + prices[j]) |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return dp[rodLength] |
| 23 | +} |
| 24 | + |
| 25 | +fun main() { |
| 26 | + // Example usage |
| 27 | + val lengths = intArrayOf(1, 2, 3, 4, 5) |
| 28 | + val prices = intArrayOf(2, 5, 9, 6, 8) |
| 29 | + val rodLength = 5 |
| 30 | + |
| 31 | + val result = maxRodCuttingProfit(lengths, prices, rodLength) |
| 32 | + println("Maximum Rod Cutting Profit: $result") |
| 33 | +} |
| 34 | + |
| 35 | +//2. Coin Change |
| 36 | +fun minCoinsToMakeChange(coins: IntArray, amount: Int): Int { |
| 37 | + val n = coins.size |
| 38 | + |
| 39 | + // Create a 1D array to store the minimum number of coins for each amount |
| 40 | + val dp = IntArray(amount + 1) { Int.MAX_VALUE } |
| 41 | + |
| 42 | + // Initialization: Zero coins needed to make change for amount 0 |
| 43 | + dp[0] = 0 |
| 44 | + |
| 45 | + // Populate the array using the Unbounded Knapsack approach |
| 46 | + for (i in 1..amount) { |
| 47 | + for (j in 0 until n) { |
| 48 | + if (coins[j] <= i && dp[i - coins[j]] != Int.MAX_VALUE) { |
| 49 | + dp[i] = minOf(dp[i], dp[i - coins[j]] + 1) |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return if (dp[amount] == Int.MAX_VALUE) -1 else dp[amount] |
| 55 | +} |
| 56 | + |
| 57 | +fun main() { |
| 58 | + // Example usage |
| 59 | + val coins = intArrayOf(1, 2, 5) |
| 60 | + val amount = 11 |
| 61 | + |
| 62 | + val result = minCoinsToMakeChange(coins, amount) |
| 63 | + println("Minimum Coins to Make Change: $result") |
| 64 | +} |
| 65 | + |
| 66 | + |
| 67 | +/* |
| 68 | +Rod Cutting: |
| 69 | +The maxRodCuttingProfit function calculates the maximum profit that can be obtained by cutting a rod of a given length into pieces |
| 70 | +of different lengths, each with its corresponding price. |
| 71 | +It uses a 1D array to store the maximum profit for each possible rod length. |
| 72 | +Coin Change: |
| 73 | +The minCoinsToMakeChange function calculates the minimum number of coins needed to make change for a given amount using a set of coin |
| 74 | +denominations. It uses a 1D array to store the minimum number of coins for each possible amount. |
| 75 | +
|
| 76 | +*/ |
0 commit comments