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
23 changes: 23 additions & 0 deletions coin_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Time Complexity : O(m * n) n:number of coins, m: amount
# Space complexity :O(m) m: amount
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : converting recurrsive solution to dp soltion was hard.

# Your code here along with comments explaining your approach
# create an array (dp) where every index represents a target amount and fill it with amount + 1 that represents infinity.
# Loop through every amount from 1 to target,checking each coin to see if using that will result in fewer coins than the current best.
# Once the array is fully populated look at the very last index (dp[amount]); if it’s still "infinity," the amount is impossible to make else that index is the answer.
def coinChange(coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""

dp = [amount + 1] * (amount + 1)
dp[0] = 0
for a in range(1,amount + 1):
for c in coins:
if a - c >= 0:
dp[a] = min(dp[a], 1+dp[a-c])
return dp[amount] if dp[amount] != amount + 1 else -1
30 changes: 30 additions & 0 deletions house_robber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Time Complexity : O(N) N:length of array.
# Space complexity :O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Took some time to reach pointer solution.

# Your code here along with comments explaining your approach
# Keep track of two values, option2(maximum loot from two houses ago) and option1(maximum loot from one house ago).
# For every house value n in the list, calculate a new maximum i.e either skip the current house or rob it.
# swap and return option1 at the end.

class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

if not nums:
return 0
if len(nums) == 1:
return nums[0]

option1, option2 = 0, 0

for num in nums:
new_rob = max(option1, option2 + num)
option2 = option1
option1 = new_rob

return option1