LeetCode 1473: Paint House III Solution
Master LeetCode problem 1473 (Paint House III), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1473. Paint House III
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming with three states: house index, number of neighborhoods formed so far, and the last color used. We can iterate through each house, each neighborhood count, and each color to find the minimum cost. We also need to handle cases where the current house is already painted.
- Time Complexity: O(m * n * target * n) where m is the number of houses, n is the number of colors, and target is the given number of neighborhoods.
- Space Complexity: O(m * target * n) for the DP array.
Solution Code
class Solution {
public int minCost(int[] houses, int[][] cost, int m, int n, int target) {
int[][][] dp = new int[m + 1][target + 1][n + 1];
int INF = 1000000000;
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= target; j++) {
for (int k = 0; k <= n; k++) {
dp[i][j][k] = INF;
}
}
}
dp[0][0][0] = 0;
for (int i = 1; i <= m; i++) {
for (int t = 1; t <= target; t++) {
int color = houses[i - 1];
for (int j = 1; j <= n; j++) {
if (color != 0 && color != j) {
continue;
}
int costCurrColor = (color == 0) ? cost[i - 1][j - 1] : 0;
for (int p = 1; p <= n; p++) {
if (j == p) {
dp[i][t][j] = Math.min(dp[i][t][j], dp[i - 1][t][p] + costCurrColor);
} else if (t > 1) {
dp[i][t][j] = Math.min(dp[i][t][j], dp[i - 1][t - 1][p] + costCurrColor);
}
}
}
}
}
int minCost = INF;
for (int j = 1; j <= n; j++) {
minCost = Math.min(minCost, dp[m][target][j]);
}
return (minCost == INF) ? -1 : minCost;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1473 (Paint House III)?
This page provides optimized solutions for LeetCode problem 1473 (Paint House III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1473 (Paint House III)?
The time complexity for LeetCode 1473 (Paint House III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1473 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1473 in Java, C++, or Python.