Problem Description
Given n houses and a cost matrix where costs[i][j] represents the cost of painting house i with one of three colors (red, blue, or green), find the minimum cost to paint all houses such that no two adjacent houses have the same color.
Key Insights
- The choice for painting each house depends on the previous house's color choices.
- Use dynamic programming to accumulate the cost while ensuring adjacent houses do not have the same color.
- The state of each house can be represented by the minimum cost when the house is painted a specific color, computed using the minimal costs of the previous house from the other two colors.
- The problem only requires updating the cost matrix in-place for optimal space usage.
Space and Time Complexity
Time Complexity: O(n), where n is the number of houses. Space Complexity: O(1) extra space if the input matrix is modified in place.
Solution
We use a dynamic programming approach with iterative in-place updating of the cost matrix. For each house starting from the second one, we update the cost for each color by adding the minimal cost of painting the previous house with either of the other two colors. This guarantees we never use the same color for adjacent houses while accumulating the minimal total cost. The final answer is the minimum value for the last house.