Ad platform~40 min2s · 256 MBtarget O(n^3) time, O(n^2) spaceclassic twin: lc-664dp
An outdoor ad company shows one creative across a row of billboard panels. A paint lift runs along the row. In one pass it paints a stretch of neighbouring panels in a single colour, and it paints over whatever was there.
The row starts blank, and every panel has a target colour. Your team lead asks: "What is the fewest number of passes that gives every panel its target colour?"
Write min_passes(panels).
panels[i] is the target colour of panel i, as a colour id.Input: panels = [1, 2, 1, 3]
Output: 3Let passes[i][j] be the fewest passes that paint panels i to j and nothing outside them. A panel either gets a pass of its own, or shares the pass of an earlier panel with the same colour.
| Stretch | Own pass for the first panel | Shared with a later panel | passes[i][j] |
|---|---|---|---|
| 0 to 0, 1 to 1, 2 to 2, 3 to 3 | 1 | none | 1 each |
| 0 to 1 | 2 | none | 2 |
| 1 to 2 | 2 | none | 2 |
| 2 to 3 | 2 | none | 2 |
| 0 to 2 | 3 | panel 0 with panel 2: 1 + 1 = 2 | 2 |
| 1 to 3 | 3 | none | 3 |
| 0 to 3 | 4 | panel 0 with panel 2: 2 + 1 = 3 | 3 |
The best plan paints all of panels 0 to 2 in colour 1, paints panel 1 in colour 2, and paints panel 3 in colour 3.
Input: panels = [3, 1, 3, 1, 3]
Output: 3Paint the whole row in colour 3. Then paint panel 1 and panel 3 in colour 1. That is 3 passes, and two passes cannot do it.
Input: panels = [4, 4, 4, 4]
Output: 1One pass paints the whole row in colour 4.
1 ≤ len(panels) ≤ 1001 ≤ panels[i] ≤ 1,000The number of pass sequences grows very fast. Even for a row of 7 panels with 3 colours, trying them all means searching up to 16,384 rows.
A table of stretches has about n × n / 2 = 5,000 entries. Each entry looks at up to 99 later panels, so a cubic method takes about 170,000 steps for 100 panels.