734. Paint the Row

Medium3.5 points estimatedMatrixDynamic Programming3 hints

A mural team paints a long row of n shopfronts, side by side, in one of three shades: sunrise, teal or plum. Neighbouring shopfronts must never share a shade. The table costs has one row per shopfront; costs[i][j] is the price of painting shopfront i in shade j.

Return the minimum total price needed to paint the entire row so that no two adjacent shopfronts have the same shade. A row with a single shopfront simply uses its cheapest shade.

Aim for time O(n) and extra space O(1).

Example 1

Input:
costs = [[8,3,6],[2,9,4],[7,1,5]]
Output:
6
Explanation:

Painting shade 1, 0, 1 costs 3 + 2 + 1 = 6, and no valid order does better.

Example 2

Input:
costs = [[2,2,2],[2,2,2]]
Output:
4
Explanation:

Any two different shades cost 4 in total.

Example 3

Input:
costs = [[5,1,9],[1,8,8],[4,4,1],[9,1,2]]
Output:
4
Explanation:

Shades 1, 0, 2, 1 cost 1 + 1 + 1 + 1 = 4.

Constraints

1 ≤ n = costs.length ≤ 5 * 104

costs[i].length = 3

0 ≤ costs[i][j] ≤ 1000

The answer fits in a 32-bit signed integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…