From 73b3a85e740e065e843538e888d1215d76bb8580 Mon Sep 17 00:00:00 2001 From: Priya <40591285+lakshmiPriya99@users.noreply.github.com> Date: Sat, 8 Aug 2026 14:54:06 -0500 Subject: [PATCH] Complete DP-1 exercises --- Exercise_1.py | 27 +++++++++++++++++++++++++++ Exercise_2.py | 21 +++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Exercise_1.py create mode 100644 Exercise_2.py diff --git a/Exercise_1.py b/Exercise_1.py new file mode 100644 index 00000000..4a02866a --- /dev/null +++ b/Exercise_1.py @@ -0,0 +1,27 @@ +# Time Complexity : O(amount * n), where n is the number of coin types. +# Space Complexity : O(amount) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : I had to initialize unreachable amounts clearly so they do not look like valid answers. +# Approach: I used a one-dimensional DP array where dp[i] stores the fewest coins needed for amount i. +# For each amount, I tried every coin that can fit and used the best previously solved amount. +# If the final amount is still unreachable, I returned -1. + + +class Solution: + + def coinChange(self, coins, amount): + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + + for current_amount in range(1, amount + 1): + for coin in coins: + if coin <= current_amount: + dp[current_amount] = min( + dp[current_amount], + dp[current_amount - coin] + 1 + ) + + if dp[amount] == amount + 1: + return -1 + + return dp[amount] diff --git a/Exercise_2.py b/Exercise_2.py new file mode 100644 index 00000000..05cbda82 --- /dev/null +++ b/Exercise_2.py @@ -0,0 +1,21 @@ +# Time Complexity : O(n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : The main decision was keeping only the previous two states instead of a full DP array. +# Approach: At each house, I choose between robbing it with the best value from two houses back or skipping it. +# Two variables are enough because the current answer only depends on the previous two answers. +# After processing all houses, the latest value is the maximum money that can be robbed. + + +class Solution: + + def rob(self, nums): + two_back = 0 + one_back = 0 + + for money in nums: + current = max(one_back, two_back + money) + two_back = one_back + one_back = current + + return one_back