Minimum Cost to Paint a Row of Houses With k Colors and No Two Neighbors Matching
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
Overview: Compute the minimum cost to paint a row of houses with k colors so that no two adjacent houses share a color. The problem tests dynamic programming and how to keep the per-house work small as the number of colors grows.
Constraints
- n == len(costs)
- k == len(costs[i]) for every i
- 1 <= n <= 100
- 2 <= k <= 20
- 1 <= costs[i][j] <= 20
- The answer is at most 2000, so it fits in a 32-bit signed integer
Examples
Input: ([[1, 5, 3], [2, 9, 4]],)
Expected Output: 5
Explanation: Source example 1: color 0 then color 2 (1 + 4) and color 2 then color 0 (3 + 2) both cost 5; the neighbors cannot both take color 0.
Input: ([[1, 3], [2, 4]],)
Expected Output: 5
Explanation: Source example 2: two colors force alternation, and both alternations cost 5.
Hints
- Only houses i and i + 1 constrain each other. When you choose the color of house i, what do you need to know about the houses before it?
- Houses that are not neighbors may share a color, so the cheapest color can be used many times in one optimal painting.
- A row can have its cheapest cost in two different colors. Make sure a tie like that does not stop a neighbor from using the cheap price.