diff --git a/CoinChange2.java b/CoinChange2.java new file mode 100644 index 00000000..8542889e --- /dev/null +++ b/CoinChange2.java @@ -0,0 +1,43 @@ +// 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 + + +// Your code here along with comments explaining your approach +class Solution { + public int change(int amount, int[] coins) { + + //coin change 1 we had to find min no of ways to make amt + //Here we have to find total num of ways to make amt + int m = coins.length; + int n = amount; + + int[][] dp = new int[m + 1][n + 1]; + + //amount = 0 will always be reached in 1 way + dp[0][0] = 1; + + //case 1:- dp[idx][amount] = dp[idx][amount - coins[idx]] (Choose coin) + //case 2:- dp[idx][amount] = dp[idx - 1][amount] (Do not choose coin) + + //Traversing through coins + for(int i = 1; i <= m; i++) { + + //Traversing through each amount + for(int j = 0; j <= n; j++) { + + //if the coin is greater than amount then we avoid that coin + if(coins[i - 1] > j) + dp[i][j] = dp[i - 1][j]; + + else { + dp[i][j] = dp[i][j - coins[i - 1]] + dp[i - 1][j]; + } + } + } + + //last index + return dp[m][n]; + } +} \ No newline at end of file diff --git a/PaintHouse.java b/PaintHouse.java new file mode 100644 index 00000000..89ddedec --- /dev/null +++ b/PaintHouse.java @@ -0,0 +1,36 @@ +// Time Complexity : O(2 * N) where N = number of houses +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +class Solution { + public int minCost(int[][] costs) { + + //This is the Paint house pattern in DP + //As the input is 1 we will use 1D array + int dp[] = new int[3]; + int n = costs.length; + + //instead of dp[] we can also use varR, varB, varG + dp[0] = costs[n - 1][0]; + dp[1] = costs[n - 1][1]; + dp[2] = costs[n - 1][2]; + + //we will start from bottom + for(int i = n - 2; i >= 0; i--) { + + int tempRed = dp[0]; + dp[0] = costs[i][0] + Math.min(dp[1], dp[2]); + + int tempBlue = dp[1]; + dp[1] = costs[i][1] + Math.min(tempRed, dp[2]); + + dp[2] = costs[i][2] + Math.min(tempRed, tempBlue); + } + + //the min cost of painting house with each color + return Math.min(dp[0], Math.min(dp[1], dp[2])); + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index 1739a9cb..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach