From 559f3c5d1117c05a818063ee70a6bbab25195794 Mon Sep 17 00:00:00 2001 From: Shreya Rathore Date: Wed, 26 Nov 2025 11:14:01 -0500 Subject: [PATCH] Completed exercise 1 and 2 --- CoinChange.java | 34 ++++++++++++++++++++++++++++++++++ HouseRobber.java | 27 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 CoinChange.java create mode 100644 HouseRobber.java diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..48df5111 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,34 @@ +// Time Complexity: O(mn) +// Space Complexity: O(mn) + +// 1: We maintain a dp table where dp[i][j] contains the total coins we have used to make amount j using coins i so far available to us +// 2: We check to make sure that the denomination is greater than the amount, else we will only have case0 +// 3: If not, we add case0 and case1 to have the total running sum through which we can return the last element of the dp table +class Solution { + public int coinChange(int[] coins, int amount) { + if(coins.length == 0 || coins == null) return -1; + int n = coins.length; + int m = amount; + int[][]dp = new int[n+1][m+1]; + for(int i = 1;i<=m; i++){ + dp[0][i] = amount+1; + } + for(int i = 1; i<=n;i++){ + for(int j=1; j<=m; j++){ + // when denomination > amount + if(coins[i-1] > j){ + dp[i][j] = dp[i-1][j]; + } + else + { + dp[i][j] = Math.min(dp[i-1][j], 1 + dp[i][j - coins[i-1]]); + } + } + } + int res = dp[n][m]; + if(res > amount){ + return -1; + } + return res; + } +} \ No newline at end of file diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..5fbb8e64 --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,27 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// 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 +// 1: We maintain variables to calculate the max amount the robber can make +// 2: We have prev and curr pointers that hold the max amount while iterating through the array +// 3: Once we have completed iteration, we return the curr amount which holds the total max value that the robber could make +class Solution { + public int rob(int[] nums) { + if(nums.length == 1) return nums[0]; + + int n = nums.length; + int prev = nums[0]; + int curr = Math.max(nums[0], nums[1]); + + for(int i = 2; i