From ae3da8d8e79685b9de2cca46dc9d1e589f176edf Mon Sep 17 00:00:00 2001 From: Ayush Chaudhary Date: Sat, 13 Jun 2026 14:06:15 -0500 Subject: [PATCH] Implement Coin change and House Robber --- CoinChange.java | 37 +++++++++++++++++++++++++++++++++++++ HouseRobber.java | 19 +++++++++++++++++++ Sample.java | 7 ------- 3 files changed, 56 insertions(+), 7 deletions(-) create mode 100644 CoinChange.java create mode 100644 HouseRobber.java delete mode 100644 Sample.java diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..eab9a8a6 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,37 @@ +// Time Complexity : O(mxn) +// Space Complexity : O(amount) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this :no + + +// Your code here along with comments explaining your approach + +//Using the DP we will set the for each coin we will asign hingher value than amount and +//find the minimum coins for amount j is either the old answer, or using this coin plus +// the best answer for the remaining amount. + +class CoinChange{ + public int coinChange(int[] coins, int amount) { + + int n = coins.length; + int []dp = new int[amount+1]; + + for(int i = 1; i <= amount; i++){ + dp[i] = amount+1; + } + + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= amount; j++){ + if(coins[i-1] <= j){ + dp[j] = Math.min(dp[j], dp[j-coins[i-1]]); + } + } + } + + if(dp[amount] > amount){ + return -1; + } + + return dp[amount]; + } +} diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..3486884c --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,19 @@ +public class HouseRobber { + public int rob(int[] nums) { + + int n = nums.length; + + if(n == 1) return nums[0]; + int prev = nums[0]; + int curr = Math.min(prev, nums[1]); + + for(int i = 2; i < n; i++){ + int temp =curr; + curr = Math.max(prev+nums[i], curr); + prev = curr; + } + + return curr; + + } +} diff --git a/Sample.java b/Sample.java deleted file mode 100644 index 1739a9cb..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach