There is a row of n houses, and each house must be painted one of three colors: red, blue or green. The cost of painting a house depends on both the house and the color. You have to paint all the houses so that no two adjacent houses have the same color.
The costs are given as an n x 3 matrix costs, where costs[i][j] is the cost of painting house i with color j. For example, costs[0][0] is the cost of painting house 0 red, and costs[1][2] is the cost of painting house 1 green.
Return the minimum total cost to paint all the houses.
Function Signature
def min_cost(costs: list[list[int]]) -> int:
Rules
-
Column
0
is red, column
1
is blue and column
2
is green.
-
Only houses
i
and
i + 1
count as adjacent. The row does not wrap around, so the first and last houses may share a color when
n > 2
.
-
Return only the minimum total cost, not the colors chosen.
Constraints
-
n == len(costs)
-
len(costs[i]) == 3
-
1 <= n <= 100
-
1 <= costs[i][j] <= 20
Examples
Input: costs = [[17, 2, 17], [16, 16, 5], [14, 3, 19]]
Output: 10
Painting house 0 red or green costs 17 by itself, so house 0 is blue (2). House 1 then takes green at 5 (red would cost 16), and house 2 takes blue at 3, for a total of 2 + 5 + 3 = 10.
Input: costs = [[7, 6, 2]]
Output: 2
A single house has no neighbor to conflict with, so it gets its cheapest color, green at 2.
Input: costs = [[1, 5, 3], [2, 9, 4]]
Output: 5
Red is the cheapest color for both houses, but they are adjacent, so they cannot both be red. Red then green (1 + 4) and green then red (3 + 2) both cost 5, and none of the other four valid pairs is cheaper.