From 788c98e6d87439d6ee64dc8abc52da302317e4c7 Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Thu, 12 Feb 2026 21:39:25 -0800 Subject: [PATCH] Completed dp-1 --- CoinChange.py | 21 +++++++++++++++++++++ HouseRobber.py | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 CoinChange.py create mode 100644 HouseRobber.py diff --git a/CoinChange.py b/CoinChange.py new file mode 100644 index 00000000..24155985 --- /dev/null +++ b/CoinChange.py @@ -0,0 +1,21 @@ +# Time Complexity : O(m*n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : dp[i] is the min coins to make amount i. +# For each coin, update the array by either using coin or skipping it. +# At the end, if dp[n] is still inf, it means amount can’t be formed. + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [float('inf')] * (amount + 1) + dp[0] = 0 + + for coin in coins: + for a in range(coin, amount + 1): + dp[a] = min(dp[a], dp[a-coin] + 1) + + if dp[amount] == float('inf'): + return -1 + + return dp[amount] \ No newline at end of file diff --git a/HouseRobber.py b/HouseRobber.py new file mode 100644 index 00000000..59ae818c --- /dev/null +++ b/HouseRobber.py @@ -0,0 +1,21 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : dp[i] is the max amount robbed. +# For each house, update the array by either robbing it or skipping it. + +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + return 0 + + n = len(nums) + maxRobbedAmt = [None] * (n + 1) + + maxRobbedAmt[n], maxRobbedAmt[n-1] = 0, nums[n-1] + + for i in range(n-2, -1, -1): + maxRobbedAmt[i] = max(maxRobbedAmt[i+1], maxRobbedAmt[i+2] + nums[i]) + + return maxRobbedAmt[0] \ No newline at end of file