diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..a3e608b3 --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,67 @@ +// Time Complexity : O(N) +// Space Complexity : O(N) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : + + +// Your code here along with comments explaining your approach +class Solution { + public int coinChange(int[] coins, int amount) { + // 2D DP + // // 0 to coins is row + // // 0 to amount is col + // int[][] dp = new int[coins.length+1][amount+1]; + // // set first row (coin 0) to max value - coz we are considering min + // // we can consider amount+1 as max value + // for(int i = 1; i <= amount; i++) + // { + // dp[0][i] = amount+1; + // } + + // for(int i = 1; i <= coins.length; i++) + // { + // for(int j = 0; j <= amount; j++) + // { + // if(coins[i-1] > j) + // { + // // as value as the grid above + // dp[i][j] = dp[i-1][j]; + // } + // else + // { + // dp[i][j] = Math.min(dp[i-1][j], 1+ dp[i][j - coins[i-1]]); + // } + // } + // } + + // if(dp[coins.length][amount] >= amount + 1) + // { + // return -1; + // } + // return dp[coins.length][amount]; + + // 1D DP + int dp[] = new int[amount+1]; + for(int i = 1; i <= amount; i++) + { + dp[i] = amount+1; + } + for(int i = 1; i <= coins.length; i++) + { + for(int j = 0; j <= amount; j++) + { + if(coins[i - 1] > j) + { + dp[j] = dp[j]; + } + else + { + dp[j] = Math.min(dp[j], dp[j- coins[i-1]] + 1); + } + } + } + if(dp[amount] >= amount+1) return -1; + return dp[amount]; + } +} + diff --git a/HouseRobber.java b/HouseRobber.java new file mode 100644 index 00000000..c45755e5 --- /dev/null +++ b/HouseRobber.java @@ -0,0 +1,37 @@ +// Time Complexity : O(N) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : +// Any problem you faced while coding this : + + +// Your code here along with comments explaining your approach + +class Solution { + public int rob(int[] nums) { + // 1D array + // 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(nums[i] + dp[i-2], dp[i-1]); + // } + // return dp[nums.length - 1]; + + // two variables + if(nums.length == 1) return nums[0]; + int prev = nums[0]; + int curr = Math.max(nums[0], nums[1]); + + for(int i = 2; i < nums.length; i++) + { + int temp = Math.max(curr, prev+nums[i]); + prev = curr; + curr = temp; + } + + return curr; + } +} \ No newline at end of file