diff --git a/coinchange.py b/coinchange.py new file mode 100644 index 00000000..5756230e --- /dev/null +++ b/coinchange.py @@ -0,0 +1,20 @@ +from typing import List +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + # dp = [0,1,1,2,2,1,2,2,3,3,2,3] + + for a in range(1, amount + 1): + for c in coins: + if a - c >= 0: + dp[a] = min(dp[a], 1 + dp[a - c]) + + if dp[-1] != (amount + 1): + return dp[-1] + return -1 + + # A = amount + # N = number of coins + # TC = O(A+N) + # SC = O(A) DP array has amount+1 number of entries \ No newline at end of file diff --git a/houserobber.py b/houserobber.py new file mode 100644 index 00000000..5cee5117 --- /dev/null +++ b/houserobber.py @@ -0,0 +1,21 @@ +class Solution: + def rob(self, nums): + n = len(nums) + if n == 1: + return nums[0] + dp = [0] * n + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + prev2 = 0 + prev1 = 0 + + for money in nums: + curr = max(prev1, prev2 + money) + prev2 = prev1 + prev1 = curr + + return prev1 + + # TC O(n) + # SC O(1) # if you use DP it's O(n) This is space optimized pointers version \ No newline at end of file