Ad platform~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-213dp
An ad platform sells banner spots on the stalls of a street market. The stalls stand in a circle around a square, and each stall has a booking value. Banners on two neighbouring stalls face each other and clash, so a plan never books two neighbours. The last stall stands next to the first.
Your team lead asks: "Which stalls give the largest total booking value?"
Write best_circle_total(values).
values[i] is the booking value of stall i. Stall i and stall i + 1 are neighbours, and so are the last stall and stall 0.Input: values = [4, 1, 6, 3, 5]
Output: 11The first and last stalls clash, so a plan leaves out at least one of them. Solve two lines instead: stalls 0 to 3 (leave out the last), and stalls 1 to 4 (leave out the first). Keep the larger answer.
On a line, let take be the best total of a plan that books the last stall passed. Let skip be the best total of a plan that does not. For the next stall, take = skip + value and skip = max(take, skip), both from the old values.
Line A, stalls 0 to 3 (values [4, 1, 6, 3]):
| Stall | Value | take | skip |
|---|---|---|---|
| 0 | 4 | 0 + 4 = 4 | max(0, 0) = 0 |
| 1 | 1 | 0 + 1 = 1 | max(4, 0) = 4 |
| 2 | 6 | 4 + 6 = 10 | max(1, 4) = 4 |
| 3 | 3 | 4 + 3 = 7 | max(10, 4) = 10 |
The best on line A is 10.
Line B, stalls 1 to 4 (values [1, 6, 3, 5]):
| Stall | Value | take | skip |
|---|---|---|---|
| 0 | 1 | 0 + 1 = 1 | max(0, 0) = 0 |
| 1 | 6 | 0 + 6 = 6 | max(1, 0) = 1 |
| 2 | 3 | 1 + 3 = 4 | max(6, 1) = 6 |
| 3 | 5 | 6 + 5 = 11 | max(4, 6) = 6 |
The best on line B is 11. The answer is 11.
Input: values = [2, 3, 2]
Output: 3All three stalls are neighbours of each other. A plan books one stall, and the best is the 3.
Input: values = [5, 1, 1, 5]
Output: 6The two 5s are neighbours in the circle, so a plan cannot book both. The best plan books a 5 and a 1, for 6.
1 ≤ len(values) ≤ 100,0000 ≤ values[i] ≤ 10,000There can be 100,000 stalls. Each stall is booked or not, so there are about 1.6 to the power n valid plans, and trying them all never finishes. Two passes of one small step per stall cost about 200,000 steps.