|
| 1 | +package com.kishan.scala.leetcode.juneChallenges |
| 2 | + |
| 3 | + |
| 4 | +/* |
| 5 | +* You are given coins of different denominations and a total amount of money. |
| 6 | +* Write a function to compute the number of combinations that make up that amount. |
| 7 | +* You may assume that you have infinite number of each kind of coin. |
| 8 | +*/ |
| 9 | + |
| 10 | + |
| 11 | +/* |
| 12 | +* Input: amount = 5, coins = [1, 2, 5] |
| 13 | + Output: 4 |
| 14 | + Explanation: there are four ways to make up the amount: |
| 15 | + 5=5 |
| 16 | + 5=2+2+1 |
| 17 | + 5=2+1+1+1 |
| 18 | + 5=1+1+1+1+1 |
| 19 | +* */ |
| 20 | + |
| 21 | +/* |
| 22 | +* Approach: Dynamic Programming |
| 23 | +* |
| 24 | +* Assume above inputs. Creating Empty MultiDimensional Array filled with 0(Space complexity -> 0(n+1*m+1)) |
| 25 | +* n -> Length coins array |
| 26 | +* m -> value of the amount |
| 27 | +* |
| 28 | +* 0,1,2,3,4,5 |
| 29 | +* [ |
| 30 | +* 0 -> [1, 0, 0, 0, 0, 0] |
| 31 | +* 1 -> [1, 1, 1, 1, 1, 1] |
| 32 | +* [1,2] -> [1, 1, 1+1, 1+1, 1+2, 1+2] |
| 33 | +* [1,2,5] -> [1, 1, 2, 2, 3, 3+1] |
| 34 | +* ] |
| 35 | +* |
| 36 | +* In order to get the probability we have use the below formula |
| 37 | +* element[i][j] = element[i-1][j] |
| 38 | +* when we have difference of j and coin is greater than 0 we have to get the value from the same row for the corresponding index and we have to add it to current index |
| 39 | +* element[i][j] = element[i-1][j] + element[i][j-coin] |
| 40 | +*/ |
| 41 | + |
| 42 | + |
| 43 | +object CoinChange2 { |
| 44 | + def main(args: Array[String]): Unit = { |
| 45 | + val amount = 5 |
| 46 | + val coins = Array(1, 2, 5) |
| 47 | + val result = changeSingleDimesionArray(amount, coins) |
| 48 | + println(result, result == 4) |
| 49 | + } |
| 50 | + |
| 51 | + // Memory Efficient |
| 52 | + def changeSingleDimesionArray(amount: Int, coins: Array[Int]): Int = { |
| 53 | + val length = coins.length |
| 54 | + var dp: Array[Int] = Array.ofDim[Int](amount + 1) |
| 55 | + dp(0) = 1 |
| 56 | + for (i <- 1 until length + 1) { |
| 57 | + for (j <- 1 until amount + 1) { |
| 58 | + if (j - coins(i - 1) >= 0) { |
| 59 | + dp(j) += dp(j - coins(i - 1)) |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + return dp(amount) |
| 64 | + } |
| 65 | + |
| 66 | + // Multi dimesional Array |
| 67 | + def change(amount: Int, coins: Array[Int]): Int = { |
| 68 | + val length = coins.length |
| 69 | + var dp: Array[Array[Int]] = Array.ofDim[Int](length + 1, amount + 1) |
| 70 | + dp.foreach(a => a(0) = 1) |
| 71 | + for (i <- 1 until length + 1) { |
| 72 | + for (j <- 1 until amount + 1) { |
| 73 | + dp(i)(j) = dp(i - 1)(j) |
| 74 | + if (j - coins(i - 1) >= 0) { |
| 75 | + dp(i)(j) += dp(i)(j - coins(i - 1)) |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + return dp(length)(amount) |
| 80 | + } |
| 81 | +} |
0 commit comments