diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..f5582f08 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,38 @@ +// Time Complexity : O(n × amount) +// Space Complexity : O(n × amount) +// Did this code successfully run on Leetcode : Yes + +// - Build a DP table where dp[i][j] = minimum coins needed to make amount j using first i coin types. +// - For each coin, either skip it: dp[i-1][j], or take it: dp[i][j-coin] + 1. +// - Take the minimum of both choices; if final value is amount + 1, return -1. + + + +class Solution { + public int coinChange(int[] coins, int amount) { + int[][] dp = new int[coins.length + 1][amount + 1]; + + for(int i = 1; i < amount + 1; i++) { + dp[0][i] = amount + 1; + } + + for(int i = 1; i < coins.length + 1; i++) { + for(int j = 1; j < amount + 1; j++) { + if(coins[i - 1] > j) { + dp[i][j] = dp[i -1][j]; + continue; + } + + dp[i][j] = Math.min( + dp[i -1][j], + dp[i][j - coins[i - 1]] + 1 + ); + } + } + + if(dp[coins.length][amount] == amount + 1) { + return -1; + } + return dp[coins.length][amount]; + } +} \ No newline at end of file diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..cdd9f925 --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,27 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes + +// - dp[i] stores the maximum money we can rob from houses 0...i. +// - At each house, either skip it: dp[i-1], or rob it: nums[i] + dp[i-2]. +// - Take the maximum of these two choices: dp[i] = max(dp[i-1], nums[i] + dp[i-2]) + + +class Solution { + public int rob(int[] nums) { + if(nums.length == 1) { + return nums[0]; + } + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + for(int i = 2; i < nums.length; i++) { + dp[i] = Math.max( + dp[i - 1], + nums[i] + dp[i - 2] + ); + } + + return dp[nums.length - 1]; + } +} \ No newline at end of file