diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..9c6c658f --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,25 @@ +//Coin Change +//Time Complexity: O(m*n) where m is the amount and n is the number of coins +//Space Complexity: O(m) where m is the amount + +public class CoinChange { + int dp[]; + public int coinChange(int[] coins, int amount) { + int max = amount + 1; + dp = new int[max]; + + dp[0] = 0; + for(int i = 1; i <= amount; i++) { + dp[i] = max; + } + + for(int i = 1; i <= coins.length; i++) { + for (int amt=1; amt<= amount; amt++) { + if(amt >= coins[i-1]) { + dp[amt] = Math.min(1 + dp[amt - coins[i - 1]], dp[amt]); + } + } + } + return dp[amount] == max ? -1 : dp[amount]; + } +} diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..4e9fae8f --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,21 @@ +//House Robber +//Time Complexity: O(n) +//Space Complexity: O(n) + +public class HouseRobber { + int[] dp; + public int rob(int[] nums) { + int n = nums.length; + if(n == 1) return nums[0]; + + 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], dp[i-2] + nums[i]); + } + + return dp[n-1]; + } +}