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

This file was deleted.