From f4fa0f897faba32eb8e450b0f086896667e6bb53 Mon Sep 17 00:00:00 2001 From: ashritha0806 <111675125+ashritha0806@users.noreply.github.com> Date: Tue, 21 Apr 2026 16:14:33 -0700 Subject: [PATCH] Done DP-1 --- coin_change.py | 23 +++++++++++++++++++++++ house_robber.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 coin_change.py create mode 100644 house_robber.py diff --git a/coin_change.py b/coin_change.py new file mode 100644 index 00000000..879e832b --- /dev/null +++ b/coin_change.py @@ -0,0 +1,23 @@ +# Time Complexity : O(m * n) n:number of coins, m: amount +# Space complexity :O(m) m: amount +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : converting recurrsive solution to dp soltion was hard. + +# Your code here along with comments explaining your approach +# create an array (dp) where every index represents a target amount and fill it with amount + 1 that represents infinity. +# Loop through every amount from 1 to target,checking each coin to see if using that will result in fewer coins than the current best. +# Once the array is fully populated look at the very last index (dp[amount]); if it’s still "infinity," the amount is impossible to make else that index is the answer. +def coinChange(coins, amount): + """ + :type coins: List[int] + :type amount: int + :rtype: int + """ + + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + for a in range(1,amount + 1): + for c in coins: + if a - c >= 0: + dp[a] = min(dp[a], 1+dp[a-c]) + return dp[amount] if dp[amount] != amount + 1 else -1 \ No newline at end of file diff --git a/house_robber.py b/house_robber.py new file mode 100644 index 00000000..a54c1593 --- /dev/null +++ b/house_robber.py @@ -0,0 +1,30 @@ +# Time Complexity : O(N) N:length of array. +# Space complexity :O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : Took some time to reach pointer solution. + +# Your code here along with comments explaining your approach +# Keep track of two values, option2(maximum loot from two houses ago) and option1(maximum loot from one house ago). +# For every house value n in the list, calculate a new maximum i.e either skip the current house or rob it. +# swap and return option1 at the end. + +class Solution(object): + def rob(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + + if not nums: + return 0 + if len(nums) == 1: + return nums[0] + + option1, option2 = 0, 0 + + for num in nums: + new_rob = max(option1, option2 + num) + option2 = option1 + option1 = new_rob + + return option1 \ No newline at end of file