From 6d60d9098570added79007e94a537edab2e42a53 Mon Sep 17 00:00:00 2001 From: Sristi Ingleshwar Date: Sun, 30 Nov 2025 00:13:11 -0600 Subject: [PATCH] done DP-2 --- CoinChangeII.java | 50 +++++++++++++++++++++++++++++++++++++++++++++++ PaintHouse.java | 28 ++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 CoinChangeII.java create mode 100644 PaintHouse.java diff --git a/CoinChangeII.java b/CoinChangeII.java new file mode 100644 index 00000000..a7f4e05f --- /dev/null +++ b/CoinChangeII.java @@ -0,0 +1,50 @@ +// Time Complexity : O(N) +// Space Complexity : O(N) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : + + +// Your code here along with comments explaining your approach + +class Solution { + public int change(int amount, int[] coins) { + // // 2D DP + // int[][] dp = new int[coins.length+1][amount+1]; + // dp[0][0] = 1; + // for(int i = 1; i <= coins.length; i++) + // { + // for(int j = 0; j <= amount; j++) + // { + // 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[coins.length][amount]; + + // 1D DP + int dp[] = new int[amount+1]; + dp[0] = 1; + for(int i = 1; i <= coins.length; i++) + { + for(int j = 0; j <= amount; j++) + { + if(coins[i-1] > j) + { + dp[j] = dp[j]; + } + else + { + dp[j] = dp[j] + dp[j - coins[i - 1]]; + } + } + } + return dp[amount]; + } +} \ No newline at end of file diff --git a/PaintHouse.java b/PaintHouse.java new file mode 100644 index 00000000..cf5f6ca0 --- /dev/null +++ b/PaintHouse.java @@ -0,0 +1,28 @@ +// Time Complexity : O(1) +// Space Complexity : O(M*N) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : + + +// Your code here along with comments explaining your approach + +class Solution { + public int minCost(int[][] costs) { + // 2D DP + int dp[][] = new int[costs.length][3]; + dp[0][0] = costs[0][0]; + dp[0][1] = costs[0][1]; + dp[0][2] = costs[0][2]; + + for(int i = 1; i < costs.length; 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[costs.length- 1][0] , Math.min(dp[costs.length- 1][1], dp[costs.length- 1][2])); + + // 1D DP + } +} \ No newline at end of file