diff --git a/CoinChangeII.java b/CoinChangeII.java new file mode 100644 index 00000000..52219d08 --- /dev/null +++ b/CoinChangeII.java @@ -0,0 +1,26 @@ +// Time Complexity :O(m*n) +// Space Complexity :O(m*n) +// Did this code successfully run on Leetcode :yes +// Any problem you faced while coding this :no +// Using Bottom-up Dp. + +class Solution { + public int change(int amount, int[] coins) { + int c = coins.length; + int[][] dp = new int[c+1][amount+1]; + dp[0][0] = 1;// There is only one way to make amount 0 which is pick no coins + for(int i=1; i<=c; i++){ + for(int j=0; j<=amount; j++){ + //calculating number of ways to make amount j using first i coins + if(j < coins[i-1]){ + //if amount is greater than coin value, copy value from above + dp[i][j] = dp[i-1][j]; + }else{ + //add the case where we include the coin + dp[i][j] = dp[i-1][j] + dp[i][j - coins[i-1]]; + } + } + } + return dp[c][amount]; + } +} \ No newline at end of file diff --git a/PaintHouse.java b/PaintHouse.java new file mode 100644 index 00000000..974096f3 --- /dev/null +++ b/PaintHouse.java @@ -0,0 +1,27 @@ +// Time Complexity :O(n) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode :no (premium question) +// Any problem you faced while coding this :no +// Solved using Bottom-up Dp. +// Start from the last house, and move forward calculating the min cost of painting each house in front. +// Use three variables to hold the cost of painting with three colors. + +class Solution { + public int minCost(int[][] costs) { + int m = costs.length;//number of houses + int R = costs[m-1][0]; + int B = costs[m-1][1]; + int G = costs[m-1][2]; + for(int i = m - 2; i >= 0; i--) { + int tempR = R;//store in temp variables since it is overwritten in next step + int tempB = B; + //calculate new costs based on color of i+1 th house + R = costs[i][0] + Math.min(B, G); + B = costs[i][1] + Math.min(tempR, G); + G = costs[i][2] + Math.min(tempR, tempB); + } + return Math.min(R, Math.min(B, G)); + } +} + +