Online store~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-135greedy
A market square is a ring of stalls, and each stall has a customer rating. Every stall gets at least one bonus unit. A stall rated higher than a stall next to it must get more units than that neighbour.
Each stall has two neighbours, one on each side, and the last stall is next to the first. Stalls with equal ratings have no rule between them. The market wants the fewest units in total.
Write fewest_ring_units(ratings).
ratings[i] is the rating of stall i. The stalls stand in a ring: stall i is next to stall i - 1 and stall i + 1, and stall 0 is next to the last stall.Input: ratings = [5, 1, 2, 3, 4]
Output: 15The lowest rating is 1, at stall 1. That stall is not higher than either neighbour, so it can take one unit, and the ring can be cut there. The cut ring reads 1, 2, 3, 4, 5, followed by a copy of the first stall.
| Position in the cut ring | Rating | Units after the left pass | Units after the right pass |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 2 | 2 | 2 |
| 2 | 3 | 3 | 3 |
| 3 | 4 | 4 | 4 |
| 4 | 5 | 5 | 5 |
| 5 | 1 | 1 | 1 |
The right pass raises nothing here, except that the last stall must beat the copy of the first. The total is 1 + 2 + 3 + 4 + 5 = 15.
Input: ratings = [7]
Output: 1A single stall takes one unit.
Input: ratings = [4, 4, 4]
Output: 3Equal ratings have no rule between them, so every stall takes one unit.
1 ≤ len(ratings) ≤ 100,0001 ≤ ratings[i] ≤ 1,000,000A ramp of 100,000 stalls needs units 1, 2, 3 and so on, which add up to 5,000,050,000. That is more than the largest 32-bit integer, 2,147,483,647, so the total needs 64 bits. Sweeping around the ring until nothing changes can take one sweep for each stall, which is 10,000,000,000 steps, so an algorithm with two passes is needed.