Ctrl K

A Street With Just Enough Color Blocks

Hard
A street has house_count houses in a row, and colors are numbered 1 to color_count. Some houses were painted last summer and must not be repainted. colors[i] is the color of house i, or 0 if it is still unpainted. price[i][c - 1] is the cost of painting house i in color c. A color block is a maximal run of adjacent houses with the same color. For example, the street [1, 2, 2, 3, 3, 2, 1, 1] has five blocks: [1], [2, 2], [3, 3], [2], [1, 1]. Paint every unpainted house so that the street ends up with exactly blocks blocks, and return the lowest cost. If that is impossible, return -1.
Example 1
colors=[0, 0, 0], price=[[1, 5], [4, 2], [3, 3]], house_count=3, color_count=2, blocks=1 → 8

One block means every house gets the same color. All in color 1 costs 1 + 4 + 3 = 8, all in color 2 costs 10. The answer is 8.

Example 2
colors=[0, 2, 0], price=[[1, 5], [4, 2], [3, 3]], house_count=3, color_count=2, blocks=2 → 4

House 1 is already color 2 and stays that way. Paint house 0 in color 1 (1) and house 2 in color 2 (3): [1, 2, 2] has two blocks for 4.

Example 3
colors=[1, 2, 1], price=[[1, 1], [1, 1], [1, 1]], house_count=3, color_count=2, blocks=2 → -1

Every house is already painted and there are three blocks, not two. The answer is -1.

Constraints
  • 1 ≤ house_count ≤ 100
  • 1 ≤ color_count ≤ 20
  • len(colors) = len(price) = house_count, len(price[i]) = color_count
  • 1 ≤ blocks ≤ house_count
  • 0 ≤ colors[i] ≤ color_count
  • 1 ≤ price[i][j] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardBiggest Solid Panel Block HardProfit From Two Trades HardEvery Way to Space the Words HardCrossing the Cave Hard
loading Python…
Input
colors=[0, 0, 0], price=[[1, 5], [4, 2], [3, 3]], house_count=3, color_count=2, blocks=1
Expected
8

Run checks the first 3 tests in your browser. Submit checks all 69 tests on the server, hidden ones included.