Skip to content
Open

DP 1 #2020

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
21 changes: 21 additions & 0 deletions LC198_DP_house_robber.py
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions LC322_DP_coin_change.py
Original file line number Diff line number Diff line change
@@ -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]