Skip to content
Open

DP-1 #1961

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
19 changes: 19 additions & 0 deletions coin_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
time - o(n)
space - o(n)
create an array whose length is same as amount set the zeroth index as 0. For every coin
calculate the number of ways we can achieve the amount by taking previous amount and adding 1
if we are able to get the target amount with the given coins then the array's amount index will
have a value and not the default value (+inf in this case)
"""
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')]*(amount+1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount+1):
dp[i] = min(dp[i], dp[i-coin]+1)
if dp[amount]!=float('inf'):
return dp[amount]
return -1

20 changes: 20 additions & 0 deletions house_robber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
time - o(n)
space - o(n)
create a list and add whether to rob or not to rob (what is the amount made for each decision)
when we calculate the value for robbing a house, we take previous index's not to rob value
and add the value.
if we choose not to rob, we look at what's maximum in the previous index,
finally the last index has the max value we can rob
"""
class Solution:
def rob(self, nums: List[int]) -> int:
robbed=[]
for i in range(len(nums)):
if not robbed:
robbed.append((nums[i],0)) #(choose_t0_rob,choose_not_to_rob)
else:
choose_to_rob=nums[i] + robbed[i-1][1]
choose_not_to_rob = max(robbed[i-1][1],robbed[i-1][0])
robbed.append((choose_to_rob,choose_not_to_rob))
return max(robbed[-1])