Paint House II

50 min · minCostII()

The paint catalog just grew from three colors to k. Your choices are wider, but the same neighbor rule can turn a cheap-looking color into an expensive mistake.

You're given a matrix, a grid of rows and columns, named costs. costs[i][color] is the price of painting house i with that color. Every row has the same k color columns.

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 can't share a color.
  • Every house must receive exactly one color.
  • When the street has more than one house, at least two colors are available.

Constraints

  • 1 <= costs.length <= 100
  • 1 <= k <= 20
  • Every row in costs contains exactly k integers.
  • 0 <= costs[i][color] <= 1_000
  • If costs.length > 1, then k >= 2.

Hints

Start with the direct transition

For each color at the current house, scan every different color from the previous house and extend the cheapest total you find.

Notice the repeated search

Every current color asks almost the same question: what's the smallest previous total, excluding my own color? Most colors can use one shared minimum.

Keep two winners

Record the smallest previous total, its color, and the second-smallest total. Use the second-smallest only when the current color matches the smallest total's color.

Follow-up

Could you return the chosen color for every house as well as the minimum cost? What extra history would you need to reconstruct that plan?

Visible cases

Examples

Example 1

ready
Input
costs = [
  [
    1,
    5,
    3
  ],
  [
    2,
    9,
    4
  ]
]
Expected
5
Why
red then green, or green then red, costs 5

Example 2

ready
Input
costs = [
  [
    8,
    3,
    5,
    1
  ]
]
Expected
1
Why
one house can take its cheapest color

Example 3

ready
Input
costs = [
  [
    1,
    10
  ],
  [
    10,
    1
  ],
  [
    1,
    10
  ]
]
Expected
3
Why
with two colors, the valid plan alternates

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite