Ad platform~35 min2s · 256 MBtarget O(n³) time, O(n²) spaceclassic twin: lc-312dp
An ads app shows a strip of ad slots, and each slot has a bid. When you retire a slot, you earn its bid multiplied by the bids of the two slots now next to it. A missing neighbour at either end counts as 1.
After each retirement, the slots on both sides close the gap, so they become neighbours. Your team lead asks: "In which order should we retire every slot to earn the most revenue in total?"
Write most_revenue(bids).
bids[i] is the bid of the slot at position i.i earns bids[i] × left × right, where left and right are the bids of the nearest slots still in the strip, or 1 when there is none.Input: bids = [4, 2, 5, 3]
Output: 116Put a bid of 1 at each end, which gives positions 0 to 5 with bids [1, 4, 2, 5, 3, 1]. Let best[i][j] be the most revenue from retiring every slot strictly between positions i and j, while i and j are still in the strip. For such a range, choose the slot k retired last. At that moment its neighbours are i and j, so it earns b[i] × b[k] × b[j], and the two sides best[i][k] and best[k][j] do not affect each other.
We fill by the distance j - i.
| Distance | Ranges (i, j) and their best |
|---|---|
| 2 | (0, 2): 8, (1, 3): 40, (2, 4): 30, (3, 5): 15 |
| 3 | (0, 3): 60, (1, 4): 100, (2, 5): 36 |
| 4 | (0, 4): 112, (1, 5): 112 |
| 5 | (0, 5): 116 |
For the whole strip, k = 1, 2, 3, 4 give 116, 46, 80, 115. The most is 116.
Input: bids = [7]
Output: 7One slot with two missing neighbours earns 7 × 1 × 1.
Input: bids = [1, 1, 2]
Output: 6Retire the middle slot first for 1 × 1 × 2 = 2. Then retire the first slot for 1 × 1 × 2 = 2, and last the slot with bid 2 for 1 × 2 × 1 = 2. The total is 6. Starting with the first slot earns at most 1 + 2 + 2 = 5.
1 ≤ len(bids) ≤ 2000 ≤ bids[i] ≤ 100There are n! orders, so none can be listed. A table over ranges has about n²/2 entries, and each tries up to n slots as the last one retired, so about n³/6 steps. That is about 1.35 million for n = 200, which is small.