From eeb18de83bbbc57471a1f33e92d90dce7aceb10b Mon Sep 17 00:00:00 2001 From: bansi radadiya Date: Thu, 11 Jun 2026 22:27:27 -0700 Subject: [PATCH 1/2] Done DP-1 --- CoinChange.java | 33 +++++++++++++++++++++++++++++++++ HouseRobber.java | 24 ++++++++++++++++++++++++ 2 files changed, 57 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..3ff76d69 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,33 @@ +public class CoinChange { + + public static int coinChange(int[] coins, int amount) { + int n = coins.length; + int m = amount; + int [][] dp = new int [n+1][m+1]; + for (int j = 1; j <=m; j++) { + dp[0][j] = amount +1; + } + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + 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 result = dp[n][m]; + if(result>=amount+1){ + return -1; + } + return result; + + + } + + public static void main(String[] args) { + int[] coins = {1, 2, 5}; + int amount = 11; + System.out.println(coinChange(coins, amount)); + } + +} diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..1c84c072 --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,24 @@ +public class HouseRobber { + + public static int rob(int[] nums) { + int n = nums.length; + if (n == 0) return 0; + if (n == 1) return nums[0]; + int[] dp = new int[n]; + + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + for (int i = 2; i < n; i++) { + dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]); + } + + return dp[n - 1]; + } + + public static void main(String[] args) { + int[] nums = {2, 7, 9, 3, 1}; + + System.out.println(rob(nums)); + } +} \ No newline at end of file From f6dc329e5b915a5a40f35edc2e75e015347d7fad Mon Sep 17 00:00:00 2001 From: bansi radadiya Date: Thu, 11 Jun 2026 22:29:05 -0700 Subject: [PATCH 2/2] Done DP-1 --- CoinChange.java | 3 +++ HouseRobber.java | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CoinChange.java b/CoinChange.java index 3ff76d69..f2f34262 100644 --- a/CoinChange.java +++ b/CoinChange.java @@ -31,3 +31,6 @@ public static void main(String[] args) { } } +// Output: 3 (11 can be made with 5 + 5 + 1) +// Time Complexity: O(n*m) where n is the number of coins and m is the amount. +// Space Complexity: O(n*m) for the dp array. \ No newline at end of file diff --git a/HouseRobber.java b/HouseRobber.java index 1c84c072..cfc2aab0 100644 --- a/HouseRobber.java +++ b/HouseRobber.java @@ -21,4 +21,6 @@ public static void main(String[] args) { System.out.println(rob(nums)); } -} \ No newline at end of file +} // Output: 12 (rob house 1, 3, and 5) +//Time Complexity: O(n) where n is the number of houses. +//Space Complexity: O(n) for the dp array.