From 9395007e8c473e11b11405b89908f555d4a1f3ae Mon Sep 17 00:00:00 2001 From: sainaga00 Date: Sun, 15 Mar 2026 23:37:45 -0400 Subject: [PATCH] DP-1 --- coinChange.py | 31 +++++++++++++++++++++++++++++++ houseRob.py | 18 ++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 coinChange.py create mode 100644 houseRob.py diff --git a/coinChange.py b/coinChange.py new file mode 100644 index 00000000..de388f75 --- /dev/null +++ b/coinChange.py @@ -0,0 +1,31 @@ +# Time Complexity : O(n * amount) +# Space Complexity : O(n * amount) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use recursion + memoization (top-down DP). +# At each index, we have two choices: +# 1. Pick the current coin and stay at the same index because coins can be reused. +# 2. Do not pick the current coin and move to the next index. +# Store results in a 2D memo table memo[i][amt] to avoid recomputing +# Final answer is the minimum of pick and not_pick. If result stays infinity, return -1. + + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + + def helper(i,amt,memo): + if i >= len(coins) or amt < 0: + return float('inf') + if memo[i][amt] != -1: + return memo[i][amt] + if amt == 0: + return 0 + pick = float('inf') + if amt >= coins[i]: + pick = 1 + helper(i,amt - coins[i],memo) + not_pick = helper(i + 1,amt,memo) + memo[i][amt] = min(pick, not_pick) + return memo[i][amt] + memo = [[-1 for i in range(amount + 1)]for j in range(len(coins) + 1)] + res = helper(0,amount,memo) + return -1 if res == float('inf') else res \ No newline at end of file diff --git a/houseRob.py b/houseRob.py new file mode 100644 index 00000000..bce43871 --- /dev/null +++ b/houseRob.py @@ -0,0 +1,18 @@ +# 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: Use bottom-up DP. For each house, choose the maximum between +# robbing it (nums[i] + dp[i+2]) or skipping it (dp[i+1]). +# dp[i] stores the maximum money that can be robbed starting from house i. +# The final answer is dp[0]. + + +class Solution: + def rob(self, nums: List[int]) -> int: + dp = [0 for i in range(len(nums) + 2)] + for i in range(len(nums) - 1,-1,-1): + take = nums[i] + dp[i + 2] + no_take = dp[i + 1] + dp[i] = max(take,no_take) + return dp[0] \ No newline at end of file