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
25 changes: 25 additions & 0 deletions coin_change_2.py
Original file line number Diff line number Diff line change
@@ -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]



20 changes: 20 additions & 0 deletions paint_house.py
Original file line number Diff line number Diff line change
@@ -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)