Paint House II Problem
Description
LeetCode Problem 265.
There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an n x k cost matrix costs.
- For example,
costs[0][0]is the cost of painting house0with color0;costs[1][2]is the cost of painting house1with color2, and so on...
Return the minimum cost to paint all houses.
Example 1:
Input: costs = [[1,5,3],[2,9,4]]
Output: 5
Explanation:
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
Example 2:
Input: costs = [[1,3],[2,4]]
Output: 5
Constraints:
costs.length == ncosts[i].length == k1 <= n <= 1002 <= k <= 201 <= costs[i][j] <= 20
Follow up: Could you solve it in O(nk) runtime?
Solution
Approach: Dynamic Programming with the Two Smallest Totals
As in Paint House, let f[c] be the cheapest way to paint the houses so far with the last one in color c. For the next house, f[c] becomes costs[i][c] plus the smallest previous f[c'] with c' != c. Scanning all other colors for every color takes O(k2) per house.
The follow-up asks for O(nk), and we can get it by noticing that the "smallest other value" is almost always the overall smallest. For each house we only remember three things from the previous one:
best: the smallest total,bestColor: the color that gives it,second: the second smallest total (from a different color).
Then for color c, the cheapest allowed previous total is second if c == bestColor, and best otherwise. While computing the new totals for this house, we keep track of the new best, bestColor and second the same way, so no array is needed.
Before the first house all three totals are 0 and bestColor = -1, so the first house simply takes its own costs. Because k >= 2, there is always a second smallest total.
Complexity: O(nk) time and O(1) extra space.
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
# For the houses so far: the cheapest total, its last color, and the second cheapest total.
best, best_color, second = 0, -1, 0
for row in costs:
new_best, new_color, new_second = float("inf"), -1, float("inf")
for color, cost in enumerate(row):
# Color `color` may not follow itself, so take the second best if it is the best's color.
total = cost + (second if color == best_color else best)
if total < new_best:
new_best, new_color, new_second = total, color, new_best
elif total < new_second:
new_second = total
best, best_color, second = new_best, new_color, new_second
return best