From 148b07773b74b0d22d14d344ae06b61a73e374ea Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Thu, 12 Feb 2026 21:57:19 -0800 Subject: [PATCH] completed dp2 --- CoinChange2.py | 18 ++++++++++++++++++ PaintHouse.py | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 CoinChange2.py create mode 100644 PaintHouse.py diff --git a/CoinChange2.py b/CoinChange2.py new file mode 100644 index 00000000..b1ad0697 --- /dev/null +++ b/CoinChange2.py @@ -0,0 +1,18 @@ +# Time Complexity : O(m*n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : dp[i] is number of ways to make amount i. +# dp[i] = dp[i - coin] + +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [0] * (amount + 1) + dp[0] = 1 + + for coin in coins: + for a in range(coin, amount + 1): + dp[a] += dp[a-coin] + + return dp[amount] + \ No newline at end of file diff --git a/PaintHouse.py b/PaintHouse.py new file mode 100644 index 00000000..eabe6e07 --- /dev/null +++ b/PaintHouse.py @@ -0,0 +1,27 @@ +# Time Complexity : O(n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : We work backwards from the last house. +# For each house, update the color costs based on the min of the other two colors from the next house. + +class Solution: + def minCost(self, costs: List[List[int]]) -> int: + num_houses = len(costs) + num_colors = len(costs[0]) + + costR = costs[num_houses-1][0] + costB = costs[num_houses-1][1] + costG = costs[num_houses-1][2] + + + for i in range(num_houses - 2, -1, -1): + tempR = costR + tempB = costB + + costR = costs[i][0] + min(costB, costG) + costB = costs[i][1] + min(tempR, costG) + costG = costs[i][2] + min(tempR, tempB) + + return min(costR, costB, costG) + \ No newline at end of file