From 43c90bbbe50a531611a2d6c389ca04f5fc0d134f Mon Sep 17 00:00:00 2001 From: rvuyyuru7 Date: Sat, 22 Nov 2025 21:04:15 -0600 Subject: [PATCH] DP-2 complete --- CoinChange2.java | 23 +++++++++++++++++++++++ PaintHouse.java | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 CoinChange2.java create mode 100644 PaintHouse.java diff --git a/CoinChange2.java b/CoinChange2.java new file mode 100644 index 00000000..39fc032d --- /dev/null +++ b/CoinChange2.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/coin-change-ii/ +// Approach: Similar to Coin Change I +// Optimize space using 1D array +// Time: O(coins.length * amount) +// Space: O(amount) +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; // one way to make the amount = 0 with zero coins (not choose) + for (int column = 1; column <= amount; column ++) { + // There are zero ways to make the amount > 0 with zero coins. + dp[column] = 0; + } + for (int row = 1; row <= coins.length; row ++) { + for (int column = 0; column <= amount; column ++) { + if (coins[row - 1] <= column) { // Denomation should be greater than or equal to amount + dp[column] = dp[column] + dp[column - coins[row - 1]]; // Total number of ways + } + } + } + return dp[amount]; + } +} \ No newline at end of file diff --git a/PaintHouse.java b/PaintHouse.java new file mode 100644 index 00000000..94cd160e --- /dev/null +++ b/PaintHouse.java @@ -0,0 +1,30 @@ +// Approach: Initialze costs of each color to paint the first house. +// Iterate through the next rows/houses and consider each color + min(previous house colors) +// Time complexity: O(N); N = costs.length +// Space complexity: O(1) +public class PaintHouse { + public int minCost(int[][] costs) { + int costRed = costs[0][0]; // 17 // 18 // 21 + int costBlue = costs[0][1]; // 2 // 33 // 10 + int costGreen = costs[0][2]; // 17 // 7 // 37 + for (int i = 1; i < costs.length; i ++) { + int prevCostRed = costRed; + int prevCostBlue = costBlue; + int prevCostGreen = costGreen; + costRed = costs[i][0] + Math.min(prevCostBlue, prevCostGreen); // 16 + 2 // 14 + 7 + costBlue = costs[i][1] + Math.min(prevCostRed, prevCostGreen); // 16 + 17 // 3 + 7 + costGreen = costs[i][2] + Math.min(prevCostRed, prevCostBlue); // 5 + 2 // 19 + 18 + } + return Math.min(costRed, Math.min(costBlue, costGreen)); // min of 21, 10, 7 = 7 + } + + public static void main(String[] args) { + PaintHouse paintHouse = new PaintHouse(); + int[][] costs1 = new int[][] {{17, 2, 17}, {16, 16, 5}, {14, 3, 19}}; + System.out.println(paintHouse.minCost(costs1)); + int[][] costs2 = new int[][] {{7,6,2}}; + System.out.println(paintHouse.minCost(costs2)); + int[][] costs3 = new int[][] {{17, 10, 18}, {16, 14, 15}, {11, 10, 19}, {20, 5, 7}}; + System.out.println(paintHouse.minCost(costs3)); + } +}