Ad platform~30 min2s · 256 MBtarget O(n × k) time, O(n) spacedp
You work on an ads platform that sells a banner strip made of n slots in a row. The strip is filled with ad blocks. A block of width w covers w neighbouring slots, and the widths are 1 up to k.
Each width has a price, and a block of that width always costs the same. The strip must be covered exactly, with no gaps and no overlaps. To keep the strip varied, two neighbouring blocks must not have the same width.
Your team lead asks: "What is the lowest total price of a valid strip?" The strip can have 50,000 slots.
Write cheapest_strip(n, costs).
n is the number of slots. costs[w - 1] is the price of a block of width w, for w from 1 to len(costs).n, where no two neighbouring blocks have equal widths. The same width may appear again later, as long as another width sits between.-1 when no valid strip exists.Input: n = 5, costs = [4, 3, 5]
Output: 8The widths are 1, 2 and 3, with prices 4, 3 and 5. These are all the rows of blocks that cover 5 slots with no two equal neighbours:
| Widths | Price |
|---|---|
| 1 + 3 + 1 | 4 + 5 + 4 = 13 |
| 2 + 1 + 2 | 3 + 4 + 3 = 10 |
| 2 + 3 | 3 + 5 = 8 |
| 3 + 2 | 5 + 3 = 8 |
The cheapest row costs 8.
Input: n = 4, costs = [1]
Output: -1Only width 1 is available, and four blocks of width 1 would be neighbours of equal width.
Input: n = 1, costs = [7, 1]
Output: 7One slot needs one block of width 1, which costs 7.
1 ≤ n ≤ 50,0001 ≤ len(costs) ≤ 101 ≤ costs[w - 1] ≤ 1,000,000,000Building every row of blocks takes a number of steps that grows exponentially. With 10 widths, the valid rows of 30 slots already number 8,531,821. A table with one entry for each prefix of the strip has 50,001 entries. With 10 widths, each entry needs about 10 steps.