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
26 changes: 26 additions & 0 deletions CoinChangeII.java
Original file line number Diff line number Diff line change
@@ -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];
}
}
27 changes: 27 additions & 0 deletions PaintHouse.java
Original file line number Diff line number Diff line change
@@ -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));
}
}