This problem can be efficiently solved using dynamic programming. The core idea is that the minimum cost to paint the i
-th house with a particular color depends only on the minimum costs to paint the (i-1)
-th house with the other two colors. We don't need to consider the costs of houses further back than the previous one.
Approach:
Instead of building a complete DP table, we can optimize the space complexity by only keeping track of the minimum costs for the previous house. We use three variables, r
, g
, and b
, to represent the minimum costs to paint the current house red, green, and blue, respectively. For each house, we iterate through its costs, updating these variables based on the minimum costs from the previous house.
Algorithm:
r
, g
, and b
to 0. These will store the minimum costs for each color at each step.r_new
), green (g_new
), and blue (b_new
).r_new
is the minimum of the previous house's green and blue costs, plus the current house's red cost. This is because we can't paint the current house the same color as the previous house.g_new
and b_new
.r
, g
, and b
with the newly calculated minimum costs.r
, g
, and b
.Time Complexity: O(n), where n is the number of houses. We iterate through the cost matrix once.
Space Complexity: O(1). We only use a constant amount of extra space to store the variables r
, g
, and b
.
Code Explanation (Python):
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
a = b = c = 0 # Initialize minimum costs for red, green, blue
for ca, cb, cc in costs: # Iterate through each house's costs
a, b, c = min(b, c) + ca, min(a, c) + cb, min(a, b) + cc # Update minimum costs
return min(a, b, c) # Return the overall minimum cost
The code for other languages (Java, C++, Go, JavaScript) follows the same logic with only syntax differences. They all maintain three variables to track the minimum costs and update them iteratively. The min()
function is used in all languages to find the minimum cost among the three colors at each step.
The provided solutions demonstrate a concise and efficient way to solve the Paint House problem using dynamic programming with optimized space complexity. They avoid unnecessary computations and memory usage, making them highly performant for larger input sizes.