diff --git a/coinchange2.java b/coinchange2.java new file mode 100644 index 00000000..312c9f34 --- /dev/null +++ b/coinchange2.java @@ -0,0 +1,25 @@ +// Time Complexity : O(m * n) where m is the number of coins and n is the amount. +// Space Complexity : O(n) for the DP array. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : correct order of iteration for the DP solution. +// Your code here along with comments explaining your approach: dp array of size n+1 where n is the amount. The value at dp[j] will represent the number of combinations to make up the amount j using the coins available. The base case is dp[0] = 1, which means there is one way to make up the amount 0 (using no coins). We iterate through the coins and for each coin, we iterate through the amounts from 0 to n. If the current amount j is greater than or equal to the coin value, we add the number of combinations to make up the amount j - coin value to dp[j]. Finally, we return dp[n] which will give us the number of combinations to make up the amount n. + +class Solution { + public int change(int amount, int[] coins) { + int m = coins.length; + int n = amount; + + int[] dp = new int[n+1]; + dp[0] = 1; + + for(int i=1; i<=m; i++){ + for(int j=0; j<=n; j++){ + if(j >= coins[i-1]){ + dp[j] = dp[j] + dp[j - coins[i-1]]; + } + } + } + + return dp[n]; + } +} diff --git a/painthouse.java b/painthouse.java new file mode 100644 index 00000000..0da79fa5 --- /dev/null +++ b/painthouse.java @@ -0,0 +1,26 @@ +// Time Complexity : O(m*n) where m is the number of houses and n is the number of colors. +// Space Complexity : O(m*n) for the DP table. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : the correct mapping of colors to houses. +// Your code here along with comments explaining your approach: create dp table of size m*n where m is the number of houses and n is the number of colors. The value at dp[i][j] will represent the minimum cost to paint house i with color j. The cost to paint house i with color j will be the cost of painting house i with color j plus the minimum cost of painting house i-1 with a different color. Finally, return the minimum cost to paint all houses which will be the minimum value in the last row of the dp table. + +class Solution { + public int minCost(int[][] costs) { + int m = costs.length; + int n = costs[0].length; + + int[][] dp = new int[m][n]; + + dp[0][0] = costs[0][0]; + dp[0][1] = costs[0][1]; + dp[0][2] = costs[0][2]; + + for(int i = 1; i < m; i++) { + dp[i][0] = costs[i][0] + Math.min(dp[i-1][1], dp[i-1][2]); + dp[i][1] = costs[i][1] + Math.min(dp[i-1][0], dp[i-1][2]); + dp[i][2] = costs[i][2] + Math.min(dp[i-1][0], dp[i-1][1]); + } + + return Math.min(dp[m-1][0], Math.min(dp[m-1][1], dp[m-1][2])); + } +}