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
33 changes: 33 additions & 0 deletions coin-change1.py
Original file line number Diff line number Diff line change
@@ -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]
31 changes: 31 additions & 0 deletions house-robber.py
Original file line number Diff line number Diff line change
@@ -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