Problem Description
Given n houses and k colors, where the cost of painting each house a specific color is provided in an n x k matrix, determine the minimum total cost to paint all houses such that no two adjacent houses share the same color.
Key Insights
- Use dynamic programming to compute the minimum cost to paint up to each house.
- For each house, instead of trying all colors from the previous house, track the minimum and second minimum cumulative cost from the previous house.
- If the current color is the same as the color corresponding to the previous minimum, then use the second minimum; otherwise, use the minimum.
- This trick allows reducing the nested loop over colors, achieving an O(nk) runtime.
Space and Time Complexity
Time Complexity: O(nk) Space Complexity: O(1) additional space (modifying the input matrix or using variables to store current and previous results)
Solution
The solution leverages dynamic programming where each row in the cost matrix is updated with the cumulative cost to reach that house painted with a particular color. Instead of a naïve O(n*k^2) approach, we optimize by keeping track of the smallest and second smallest cumulative costs from the previous house. When updating the cost for the current house:
- If the current color is the same as the one with the smallest cost from the previous house, add the second smallest cost.
- Otherwise, add the smallest cost. This ensures that two adjacent houses do not use the same color while still achieving the overall minimum cost.