diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..f2f34262 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,36 @@ +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)); + } + +} +// 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 new file mode 100644 index 00000000..cfc2aab0 --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,26 @@ +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)); + } +} // 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.