Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CoinChange2.kt
Original file line number Diff line number Diff line change
@@ -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]
}
}
24 changes: 24 additions & 0 deletions PaintHouse.kt
Original file line number Diff line number Diff line change
@@ -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<IntArray>): 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))
}
}