Paint House II
There is a row of n houses, where each house can be painted with one of k colors. The cost of painting each house with a certain color is represented by an n x k cost matrix costs.
Return the minimum cost to paint all houses such that no two adjacent houses have the same color.
- If
n == 0, return0. - If
k == 0, return0. - If
n == 1, return the minimum value incosts[0](equivalently the sole cost whenk == 1). - If
n > 1andk == 1, it is impossible to paint every pair of adjacent houses with different colors. In that case, return-1.
The challenge is to solve this in O(n*k) time with O(1) extra space beyond the input.
Examples
Input: [[1,5,3],[2,9,4]]
Output: 5
Input: [[1,3],[2,4]]
Output: 5
Hints
Use dynamic programming to keep track of the minimum cost to paint each house with each color, ensuring no two adjacent houses have the same color.
For each house and color, calculate the minimum cost by considering all possible colors for the previous house (excluding the current color) and adding the current cost.
Optimize the solution by maintaining only the previous row of costs (O(k) space) and updating it iteratively for each house, ensuring the overall time complexity remains O(n*k).
Related Problems
Paint House II
There is a row of `n` houses, where each house can be painted with one of `k` colors. The cost of painting each house with a certain color is represented by an `n x k` cost matrix `costs`.