diff --git a/LC198_DP_house_robber.py b/LC198_DP_house_robber.py new file mode 100644 index 00000000..f0812622 --- /dev/null +++ b/LC198_DP_house_robber.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: built a dp[i] as the minimum coins needed to make amount i, checking every coin for each amount + + +def rob(nums: list[int]) -> int: + n = len(nums) + if n == 1: + return nums[0] + prev = nums[0] + curr = max(nums[0], nums[1]) + + for i in range(2, n): + temp = curr + curr = max(temp, nums[i] + prev) + prev = temp + + return curr diff --git a/LC322_DP_coin_change.py b/LC322_DP_coin_change.py new file mode 100644 index 00000000..064b1dec --- /dev/null +++ b/LC322_DP_coin_change.py @@ -0,0 +1,26 @@ +# Time Complexity : O(n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : yes +# Any problem you faced while coding this : No + +# Approach: at each house, choosing max(skip current, rob current + money from i-2) while keeping only the previous two DP values + + +def coinChange(coins: list[int], amount: int) -> int: + m = len(coins) + n = amount + # m rows and n cols + dp = [0] * (n + 1) + + for j in range(1, n + 1): + dp[j] = 99999 + + for i in range(1, m + 1): + for j in range(n + 1): + # choose case + if j >= coins[i - 1]: + dp[j] = min(dp[j], dp[j - coins[i - 1]] + 1) + + if dp[n] == 99999: + return -1 + return dp[n]