diff --git a/CoinChange2.kt b/CoinChange2.kt new file mode 100644 index 00000000..8ff1d4fe --- /dev/null +++ b/CoinChange2.kt @@ -0,0 +1,26 @@ +// In this problem, we use DP bottom up approach to calculate the number of ways to make the amount. We use a 1D array to store the number of ways. +// If the amount is less than the coin value, we carry forward the previous value. Otherwise, we add the number of ways to make the amount by including the coin. +// Time Complexity: O(m*n) where m is the number of coins and n is the amount. +// Space Complexity: O(n) where n is the amount. + +class Solution { + fun change(amount: Int, coins: IntArray): Int { + val m = coins.size + val n = amount + + val dp = IntArray(n + 1) + dp[0] = 1 + + for(i in 1..m) { + for(j in 0..n) { + if(j < coins[i-1]) { + dp[j] = dp[j] + } else { + dp[j] = dp[j] + dp[j - coins[i - 1]] + } + } + } + + return dp[n] +} +} diff --git a/PaintHouse.kt b/PaintHouse.kt new file mode 100644 index 00000000..a8a51ebe --- /dev/null +++ b/PaintHouse.kt @@ -0,0 +1,24 @@ +// In this problem, we have 3 variables for each color tracking the cost of painting the houses. we start from the last house and move to the first house, +// updating the costs for each color based on the minimum cost of painting the next house with a different color. +// Time Complexity: O(n) where n is the number of houses. +// Space Complexity: O(1) constant extra space + +class Solution { + fun minCost(costs: Array): Int { + val n = costs.size + var cr = costs[n-1][0] + var cb = costs[n-1][1] + var cg = costs[n-1][2] + + for(i in n-2 downTo 0) { + val tmpR = cr + val tmpB = cb + + cr = costs[i][0] + Math.min(cb, cg) + cb = costs[i][1] + Math.min(tmpR, cg) + cg = costs[i][2] + Math.min(tmpR, tmpB) + } + + return Math.min(cr, Math.min(cb, cg)) + } +} \ No newline at end of file