Paint House Problem
Description
LeetCode Problem 256.
There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. 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 3 cost matrix costs.
- For example,
costs[0][0]is the cost of painting house0with the color red;costs[1][2]is the cost of painting house 1 with color green, and so on...
Return the minimum cost to paint all houses.
Example 1:
Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.
Example 2:
Input: costs = [[7,6,2]]
Output: 2
Constraints:
costs.length == ncosts[i].length == 31 <= n <= 1001 <= costs[i][j] <= 20
Solution
Approach: Dynamic Programming
Painting greedily (always the cheapest color allowed) can fail, because a cheap choice now can force an expensive one next. Instead we track, for each color, the cheapest way to paint all houses so far with the last house in that color.
Call these red, blue and green. For the next house with costs [r, b, g]:
redbecomesr + min(blue, green): the previous house must be blue or green.bluebecomesb + min(red, green).greenbecomesg + min(red, blue).
All three new values must be computed from the old ones, so update them together (or save the old values first). Start with all three at 0, and the answer is the smallest of the three after the last house.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
# red, blue, green: cheapest way to paint the houses so far with the last one in that color
red = blue = green = 0
for r, b, g in costs:
red, blue, green = r + min(blue, green), b + min(red, green), g + min(red, blue)
return min(red, blue, green)