diff --git a/coinchange.java b/coinchange.java new file mode 100644 index 00000000..8d6d5c28 --- /dev/null +++ b/coinchange.java @@ -0,0 +1,34 @@ +// Time Complexity : O(n * m) +// Space Complexity : O(n * m) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : understanding DP approach and how to fill the table was difficult for me. I had to watch a video to understand the approach and then implement it. + + +// Your code here along with comments explaining your approach: try all methods to have amount using coins from i. two options: skip coin or use it. return total combination of coins that reach zero after usage. + +class Solution { + public 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 res=dp[n][m]; + if(res>=amount+1){ + return -1; + } + return res; + } +} \ No newline at end of file diff --git a/houserobber.java b/houserobber.java new file mode 100644 index 00000000..73703d2b --- /dev/null +++ b/houserobber.java @@ -0,0 +1,24 @@ +// Time Complexity :o(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : understanding DP approach + + +// Your code here along with comments explaining your approach: 1D array to store max amount that can be robbed from 0 to i. for each house, we have two options: skip or rob. if we skip, we take the max amount from previous house. if we rob, we add current house amount to max amount from two houses back. return max amount from last house. + +class Solution { + public int rob(int[] nums) { + int n = nums.length; + 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