From 19d3917306b02e06986f77208d92c09eee7d41e4 Mon Sep 17 00:00:00 2001 From: Dheepthi-Reddy Date: Tue, 25 Nov 2025 03:32:47 -0600 Subject: [PATCH] Solved DP_1 --- CoinChange.py | 38 ++++++++++++++++++++++++++++++++++++++ HouseRobber.py | 25 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 CoinChange.py create mode 100644 HouseRobber.py diff --git a/CoinChange.py b/CoinChange.py new file mode 100644 index 00000000..885ecd4e --- /dev/null +++ b/CoinChange.py @@ -0,0 +1,38 @@ +''' +In this problem I have used exhaustive approach by using a DP table, where I stored repeated sub problems. +- Initialized a 2D array with amount as columns and coins as rows. +- By comparing the repeated sub problems same as the above elemnts sub problem in the columns and denomination steps back in the row. +- By repeating this till the amount of DP table is reached at the last element we will get the minimum no of coins needed to make up the amount. +''' +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + if len(coins) == 0 or coins is None: return -1 + n = len(coins) + m = amount + # dp = [n+1][m+1] + dp = [[0] * (m + 1) for _ in range(n + 1)] + # filling first column with infinity + for i in range(m+1): + dp[0][i] = amount+1 + # filling DP table + for i in range(1, n+1): # coins + for j in range(1, m+1): # amount + # 2 cases + # till the denomination > amount we only have case0 + if coins[i-1] > j: + dp[i][j] = dp[i-1][j] + else: + # 2 cases, cas0 & case1 + dp[i][j] = min(dp[i-1][j], 1+ dp[i][j-coins[i-1]]) + res = dp[n][m] + if(res >= amount+1): + return -1 + else: + return res + +''' +Time Complexity: O(m*n) +Since we are iterating on an 2D array of size m*n. +Space Complexity: O(m*n) +The size of the array used to store the DP table is m*n. +''' \ No newline at end of file diff --git a/HouseRobber.py b/HouseRobber.py new file mode 100644 index 00000000..ca5b9ee4 --- /dev/null +++ b/HouseRobber.py @@ -0,0 +1,25 @@ +''' +In this problem, I initialized previous value with first element of nums and current value with second element of nums. +Then, iteratively compared and updated previous and current values along the length of nums array and returned max amount at the end of iteration. +''' +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + if n == 1: return nums[0] + # storing the first element + prevMax = nums[0] + # comparing first element and second elemnt and storing the maximum of them + currentMax = max(nums[0], nums[1]) + + for i in range(2, n): + temp = currentMax + currentMax = max(currentMax, prevMax + nums[i]) + prevMax = temp + return currentMax + +''' +Time Complexity: O(n) +Since we are iterating on an array of length n +Space Complexity: O(1) +Here I only used 2 variables not any arrays to store the max values +''' \ No newline at end of file