Paint House III

HardDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are m houses in a row and n paint colors labeled 1 to n. houses[i] is the current color of house i, or 0 if it is still unpainted. Houses that are already painted keep their color and cost nothing. Painting unpainted house i with color j costs cost[i][j - 1]. After painting, a **neighborhood** is a maximal run of consecutive houses with the same color; for example, colors [1,2,2,3,3,2,1,1] form 5 neighborhoods. Return the minimum total cost to paint every unpainted house so that there are exactly target neighborhoods, or -1 if that is impossible.

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 [1,2,2,1,1]: 1 + 1 + 1 + 1 + 5 = 9, giving neighborhoods [1], [2,2], [1,1].
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 house 0 with color 2 (cost 10) and house 4 with color 2 (cost 1): [2,2,1,2,2] has 3 neighborhoods.
Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
Output: -1
All houses are fixed and already form 4 neighborhoods.

Constraints

  • m == houses.length == cost.length
  • n == cost[i].length
  • 1 <= m <= 100
  • 1 <= n <= 20
  • 1 <= target <= m
  • 0 <= houses[i] <= n and 1 <= cost[i][j] <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems