diff --git a/coin_change_2.py b/coin_change_2.py new file mode 100644 index 00000000..15ac6e05 --- /dev/null +++ b/coin_change_2.py @@ -0,0 +1,25 @@ +# 518. Coin Change 2 +# Bottom-Up Dynamic Programming +# Time Complexity: O(m*n), Space Complexity: O(n) + +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + m = len(coins) + n = amount + # Initialize dp array where dp[j] will be storing the number of combinations for amount j + dp = [0 for _ in range(n + 1)] + dp[0] = 1 + for i in range(1,m+1): + # For current coin, update all amounts >= coin. We go left-to-right so each coin can be used multiple times, + # but different orders of the same combination are not double-counted. + for j in range(n+1): + if coins[i-1]>j: + # Current coin cannot contribute to amount j + dp[j] = dp[j] + else: + # Include current coin and add ways to make amount j - coins[i-1] + dp[j] = dp[j] + dp[j-coins[i-1]] + return dp[n] + + + \ No newline at end of file diff --git a/paint_house.py b/paint_house.py new file mode 100644 index 00000000..f2e4459b --- /dev/null +++ b/paint_house.py @@ -0,0 +1,20 @@ +# 256. Paint House +# Bottom-Up Dynamic Programming +# Time Complexity: O(m), Space Complexity: O(1) + +class Solution: + def minCost(self, costs: List[List[int]]) -> int: + m = len(costs) + # Initialize with the last house's costs + costR, costG, costB = costs[m-1] + + # Move backwards through the houses + for i in range(m - 2, -1, -1): + tempR, tempG, tempB = costR, costG, costB + # For each color, choose the minimum of the other two colors for the next house and add the current cost + costR = costs[i][0] + min(tempG, tempB) + costG = costs[i][1] + min(tempR, tempB) + costB = costs[i][2] + min(tempR, tempG) + + # The minimum of the three options for the first house is the final answer + return min(costR, costG, costB)