From 43a344ac6fe1f34ad8be44cad6f998617ec83607 Mon Sep 17 00:00:00 2001 From: Aahi Awasthee Date: Sun, 21 Dec 2025 00:40:45 -0600 Subject: [PATCH] Solved DP problems --- coin-change-2.java | 27 +++++++++++++++++++++++++++ paint-house.java | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 coin-change-2.java create mode 100644 paint-house.java diff --git a/coin-change-2.java b/coin-change-2.java new file mode 100644 index 00000000..9c2d2f2b --- /dev/null +++ b/coin-change-2.java @@ -0,0 +1,27 @@ +// Time Complexity :O(n^2) +// Space Complexity : O(m*n) +// Did this code successfully run on Leetcode : Yes +// Three line explanation of solution in plain english + +// Your code here along with comments explaining your approach + +class Solution { + public int change(int amount, int[] coins) { + int m = coins.length; + int n = amount; + + int[][] dp = new int[m + 1][n + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= m; i++) { + for (int j = 0; 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]; + } +} diff --git a/paint-house.java b/paint-house.java new file mode 100644 index 00000000..5f1e1bc8 --- /dev/null +++ b/paint-house.java @@ -0,0 +1,39 @@ +public class PaintHouse { + + public int minCost(int[][] costs) { + if (costs == null || costs.length == 0) { + return 0; + } + + // Iterate bottom up from the second-to-last house to the first. + for (int i = costs.length - 2; i >= 0; i--) { + // Min cost to paint house 'i' red is its original cost plus the + // min cost of painting house 'i+1' blue or green. + costs[i][0] += Math.min(costs[i + 1][1], costs[i + 1][2]); + + // Min cost to paint house 'i' blue + costs[i][1] += Math.min(costs[i + 1][0], costs[i + 1][2]); + + // Min cost to paint house 'i' green + costs[i][2] += Math.min(costs[i + 1][0], costs[i + 1][1]); + } + return Math.min(Math.min(costs[0][0], costs[0][1]), costs[0][2]); + } + + public static void main(String[] args) { + PaintHouse solver = new PaintHouse(); + int[][] costs = {{17, 2, 17}, {16, 16, 5}, {14, 3, 19}}; + + System.out.println("The minimum cost is: " + solver.minCost(costs)); // Expected output: 10 + } +} + +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english +// used the bottom up approach to calculate the minimum costs +//stored the total cost in the row above +//Chose the minimum from the first row + +// Your code here along with comments explaining your approach \ No newline at end of file