There is a row of m houses in a small city, and each house must be painted with one of n colors (labeled from 1 to n). Some houses were painted last summer and should not be painted again.
A neighborhood is a maximal group of consecutive houses that are painted with the same color. For example, the coloring [1, 2, 2, 3, 3, 2, 1, 1] has 5 neighborhoods: {1}, {2, 2}, {3, 3}, {2}, {1, 1}.
You are given an array houses, an m x n matrix cost and an integer target, where:
-
houses[i]
is the color of house
i
, or
0
if the house is not painted yet.
-
cost[i][j]
is the cost of painting house
i
with color
j + 1
.
Return the minimum cost of painting all the remaining houses so that there are exactly target neighborhoods. If it is not possible, return -1.
Function Signature
def min_cost(houses: list[int], cost: list[list[int]], m: int, n: int, target: int) -> int:
Rules
-
A house with
houses[i] != 0
keeps that color and costs nothing. Its row in
cost
is ignored.
-
Only houses with
houses[i] == 0
are painted, and each can take any of the
n
colors.
-
Neighborhoods are counted on the final coloring of all
m
houses, including the ones painted last summer.
-
Return
-1
when no coloring of the unpainted houses gives exactly
target
neighborhoods.
Constraints
-
m == len(houses) == len(cost)
-
n == len(cost[i])
-
1 <= m <= 100
-
1 <= n <= 20
-
1 <= target <= m
-
0 <= houses[i] <= n
-
1 <= cost[i][j] <= 10^4
Examples
Input: houses = [0, 0, 0, 0, 0], cost = [[1, 10], [10, 1], [10, 1], [1, 10], [5, 1]], m = 5, n = 2, target = 3
Output: 9
Paint the houses as [1, 2, 2, 1, 1] for 1 + 1 + 1 + 1 + 5 = 9, which forms the 3 neighborhoods {1}, {2, 2}, {1, 1}. The cheapest color for every house gives [1, 2, 2, 1, 2] at cost 5, but that has 4 neighborhoods.
Input: houses = [0, 2, 1, 2, 0], cost = [[1, 10], [10, 1], [10, 1], [1, 10], [5, 1]], m = 5, n = 2, target = 3
Output: 11
Paint the unpainted houses to get [2, 2, 1, 2, 2] for 10 + 1 = 11, which forms the 3 neighborhoods {2, 2}, {1}, {2, 2}. Painting house 0 with color 1 would already create 4 neighborhoods among the first four houses.
Input: houses = [2, 0, 2], cost = [[4, 4], [3, 7], [4, 4]], m = 3, n = 2, target = 2
Output: -1
House 1 is the only one to paint. Color 1 gives [2, 1, 2] with 3 neighborhoods and color 2 gives [2, 2, 2] with 1, so exactly 2 is impossible.