Problem 517274 · medium · Level 05 Advanced Algorithms & Graphs

Three-Tint Terrace

dynamic programming · 1-D dp · min cost · adjacent constraint

A terrace of houses is being repainted with three tints: sand, sage and slate. costs[i] is a list of three integers, the price of painting house i in each tint. Neighbouring houses must not share a tint. Return the cheapest way to paint every house.

Examples

Input:  costs = [[6, 2, 9], [3, 8, 4], [7, 5, 1]]
Output: 6
Explanation: sage (2), sand (3), slate (1).

Input:  costs = [[4, 9, 3]]
Output: 3

Constraints

  • 0 <= len(costs) <= 10**5, each entry has exactly 3 prices
  • 0 <= costs[i][j] <= 10**4
  • Target complexity: O(n) time.

Goals

  • Keep one best-cost value per colour for the previous house
  • Combine 'different from the neighbour' with a running minimum
Starting Python…