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
35 changes: 35 additions & 0 deletions Coinchange2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// 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
/*
We intiially try to fill the zeroth column for all coins as 1 as they lead to happy path scenario where
the net amount is 0. Now, for every coin and amount combination, we consider choose and no choose scenario
sum. For no choose, the value of cell obtains directly from above cell.For choose scenario, we get it from
same row and column belonging to amount and coin denomination difference.
*/

class Solution {
public int change(int amount, int[] coins) {
int m = coins.length;
int n = amount;

int[][] dp = new int[m + 1][n + 1];

for(int i = 0 ; i <= m ; i++)
dp[i][0] = 1;

for(int i = 1 ; i <= m ; i++) {
for(int j = 1 ; j <= n ; j++) {
if(j < coins[i - 1])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]];
}
}
return dp[m][n];
}
}
30 changes: 30 additions & 0 deletions PaintHouse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Time Complexity : O(n)
// Space Complexity : O(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
/*
If we go bottom up, we feed the last row into our dp array and start looping from the row above and compute
by summation of cost to paint that cell's house and min cost required to paint with non adjacent colors
of the succeding row.This way, we cumulate the total sum in each row as we go up and finally choose the
minimum value from the intial row which represents the total cost.
*/

class Solution {
public int minCost(int[][] costs) {
int m = costs.length;
int[][] dp = new int[m][3];

for(int j = 0 ; j < 3 ; j++)
dp[m - 1][j] = costs[m - 1][j];

for(int i = m - 2 ; i >= 0 ; 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[0][0], Math.min(dp[0][1], dp[0][2]));
}
}