Paint House

Medium

Topics
ArrayDynamic Programming

There is a row of n houses, each to be painted one of three colours: red, blue or green. Painting each house a given colour has its own cost.

The costs are given as an n x 3 matrix costs, where costs[i][0] is the cost of painting house i red, costs[i][1] blue, and costs[i][2] green.

Return the minimum total cost to paint every house such that no two adjacent houses share a colour.

The judge names this argument grid, since it feeds every matrix problem through the same reader. It is the costs matrix above, one row per house.

Example 1

house 017217house 116165house 214319redbluegreen
one cheapest valid choice
Every cell is the price of painting that house that colour. The one rule is that neighbouring houses must differ, which is why the cheapest cell in a row is not always available — house 0 and house 1 cannot both take the colour they would each prefer if it is the same one. The shaded cells are a legal choice totalling 10, and no legal choice is cheaper.
One row per house, one column per colour.
Input:  costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Blue, green, blue costs 2 + 5 + 3. The cheapest colour per house in isolation would be 2 + 5 + 3 as well here, but only because those happen not to clash.

Example 2

house 0762redbluegreen
one cheapest valid choice
The one rule is that neighbouring houses must differ, which is why the cheapest cell in a row is not always available — with a single house there is no neighbour, so its cheapest colour wins outright.
Input:  costs = [[7,6,2]]
Output: 2
Explanation: One house has no neighbour to clash with, so take its cheapest colour.

Example 3

house 01100100house 11100100redbluegreen
one cheapest valid choice
Input:  costs = [[1,100,100],[1,100,100]]
Output: 101
Explanation: Both houses prefer red, but they are adjacent, so one of them has to take a 100.

Constraints

  • costs.length == n
  • costs[i].length == 3
  • 1 <= n <= 100
  • 1 <= costs[i][j] <= 20
  • Painting each house a colour is always allowed
Editorial — intuition, approach, complexity and pitfalls

Intuition

Taking the cheapest colour for every house independently is the obvious move and example 3 shows why it fails: two neighbours can both want red, and one of them has to give it up.

The fix comes from noticing how little history matters. Once the houses up to i are painted, the only fact about them that constrains house i + 1 is which colour house i ended up. Everything earlier is settled and cannot clash with anything still to come.

So three running totals are enough: the cheapest way to paint houses 0..i such that house i is red, the cheapest ending blue, and the cheapest ending green. Each is built from the two totals it is allowed to follow.

Approach

  1. Start the three totals at house 0’s three costs.
  2. For each later house, compute its new red total as its red cost plus the smaller of the previous blue and green totals, and symmetrically for blue and green.
  3. Replace the three totals and move on. Only the previous house’s three numbers are ever needed, so no table has to be kept.
  4. The answer is the smallest of the three totals after the last house.

Walkthrough

costs = [[17, 2,17],
         [16,16, 5],
         [14, 3,19]]

            end red   end blue   end green
house 0        17          2         17
house 1    16+min(2,17)=18   16+min(17,17)=33   5+min(17,2)=7
house 2    14+min(33,7)=21   3+min(18,7)=10     19+min(18,33)=37

smallest of 21, 10, 37  ->  10

Complexity

  • Time — O(n): one pass over the houses, with a fixed three colours of work each.
  • Space — O(1): three running totals, regardless of how many houses there are.

Common Pitfalls

  • Assigning the three new totals one at a time in a language without simultaneous assignment. Overwriting red first means the blue line then reads the new red rather than the previous house’s, which permits two adjacent reds.
  • Returning the last house’s cheapest colour cost rather than the smallest of the three accumulated totals.
  • Greedily picking each house’s cheapest colour and patching clashes afterwards. There is no local repair that is always optimal.

Full Solution — all languages

class Solution:
    def minCost(self, grid):
        red, blue, green = grid[0]
        for i in range(1, len(grid)):
            red, blue, green = (
                grid[i][0] + min(blue, green),
                grid[i][1] + min(red, green),
                grid[i][2] + min(red, blue),
            )
        return min(red, blue, green)
SensAI
Beta
Tap the mic to stop voice mode