diff --git a/coin-change1.py b/coin-change1.py new file mode 100644 index 00000000..308970f4 --- /dev/null +++ b/coin-change1.py @@ -0,0 +1,33 @@ +# Take a 1D array DP upto the length of amount+1 and assign it to infinity. Assign the first element to 0. +# For each coin in coins, and each amount from 1 to amount, if the coins are lesser than or qual to the amount, +# then update the index with the minimun of the current index or the element at the i-denomination index +1. +# At last, return -1 if the element is greater than the amount else return the element at the last column. + +# Time complexity: O(n*m) n= number of coins, m = amount +# Space complexity: O(m), m = amount + + + + +class Solution(object): + def coinChange(self, coins, amount): + """ + :type coins: List[int] + :type amount: int + :rtype: int + """ + rows = len(coins)+1 + cols = amount+1 + dp=[None for i in range(cols)] + dp[0]=0 + for i in range(1,cols): + dp[i]=float('inf') + + for i,c in enumerate(coins): + for j in range(1,cols): + if c<=j: + dp[j]=min(dp[j],dp[j-c]+1) + if dp[cols-1] >amount: + return -1 + else: + return dp[cols-1] diff --git a/house-robber.py b/house-robber.py new file mode 100644 index 00000000..e843643a --- /dev/null +++ b/house-robber.py @@ -0,0 +1,31 @@ +# Take 2 variables, prev2 and prev where prev2 is the first elememt and prev is the max between +# the first and the second element for each remaining elements in nums, check the max between +# prev2+current element and prev elememt, the max is the current element. Prev2 becomes prev1 +# and prev1 becomes current, updat the new current + +# Time complexity: O(n) +# Space complexity: O(1) + + + + +class Solution(object): + def rob(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + l=len(nums) + if l==1: + return nums[0] + if l==2: + return max(nums[0],nums[1]) + prev2=nums[0] + prev1=max(nums[1],nums[0]) + for i in range(2,l): + current = max(prev1,prev2+nums[i]) + prev2=prev1 + prev1=current + return current + + \ No newline at end of file