Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CoinChangeII.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(mn)
// Space Complexity : O(mn)
// 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
// 1: We maintain a dp table where dp[i][j] contains the total number of ways to make amount j using coins i so far available to us
// 2: We check to make sure that the denomination is greater than the amount, else we will only have case0
// 3: If not, we add case0 and case1 to have the total running sum through which we can return the last element of the dp table
class CoinChangeII {
public int change(int amount, int[] coins) {
int n = coins.length;
int m = amount;
int[][] dp = new int[n + 1][m + 1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
// denomination > amount
if (coins[i - 1] > j) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]];
}
}
}
return dp[n][m];
}
}
29 changes: 29 additions & 0 deletions PaintHouse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : No, this is a premium question
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach
// 1: We maintain a dp table for this approach that we have optimized to use only three values
// 2: The prev pointer is at dp0, current is at dp1 and next at dp2
// 3: Keeping the last row constant, we calculate the minimum cost for each color of house and then return the minimum of the three
class PaintHouse{
public int minCost(int[][] costs){
int n = costs.length;
// keeping last row constant
int dp0 = costs[n-1][0];
int dp1 = costs[n-1][1];
int dp2 = costs[n-1][2];

for(int i = 1; i<n; i++){
int temp0 = dp0;
int temp1 = dp1;
dp0 = costs[i][0] + Math.min(dp1, dp2);
dp1 = costs[i][1] + Math.min(temp1, dp2);
dp2 = costs[i][2] + Math.min(temp0, temp1);
}

return Math.min(dp0, Math.min(dp1, dp2));
}
}