Paint House

35 min · minCost()

Painting one house cheaply is easy. Painting an entire street cheaply gets interesting when every choice changes what you're allowed to do next door.

You're given a matrix, a grid of rows and columns, named costs. Row i holds the price of painting house i red, blue, or green, in that order: costs[i] = [red, blue, green].

Choose one color for every house and return the smallest possible total cost.

A few ground rules:

  • Adjacent houses are neighbors whose indices differ by one. They must receive different colors.
  • Every house must be painted exactly once.
  • A paint cost may be zero.

Constraints

  • 1 <= costs.length <= 100
  • Every row in costs contains exactly 3 integers.
  • 0 <= costs[i][color] <= 1_000

Hints

Your last choice is enough

When you reach a house, does the full painting history matter? Only the previous house's color can block your next move.

Write three running answers

Track the cheapest total ending in red, blue, and green. A new red total may extend only the previous blue or green total.

Roll the row forward

Compute all three new totals from the old three before replacing them. After the last house, the answer is the smallest of the three totals.

Follow-up

What changes when the paint shop offers k colors? Can you avoid checking all other k - 1 colors every time you update one color?

Visible cases

Examples

Example 1

ready
Input
costs = [
  [
    17,
    2,
    17
  ],
  [
    16,
    16,
    5
  ],
  [
    14,
    3,
    19
  ]
]
Expected
10
Why
blue, green, blue costs 2 + 5 + 3 = 10

Example 2

ready
Input
costs = [
  [
    5,
    8,
    6
  ]
]
Expected
5
Why
one house has no neighbor to conflict with

Example 3

ready
Input
costs = [
  [
    3,
    1,
    4
  ],
  [
    2,
    8,
    5
  ]
]
Expected
3
Why
blue then red costs 1 + 2 = 3

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite