diff --git a/coin_change.py b/coin_change.py new file mode 100644 index 00000000..af0a3937 --- /dev/null +++ b/coin_change.py @@ -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 + \ No newline at end of file diff --git a/house_robber.py b/house_robber.py new file mode 100644 index 00000000..c6535a47 --- /dev/null +++ b/house_robber.py @@ -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]) \ No newline at end of file