Ad platform~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-84monotonic-stack · stacks
An outdoor ad platform sells banner space along a street. Buildings stand side by side, each 1 metre wide, and the heights of their rooftops in metres are known.
A banner is a rectangle that covers one or more buildings that stand next to each other. It must fit under the rooftops: it can be no taller than the lowest building it covers. The platform wants the banner with the largest area, in square metres. A street can have up to 100,000 buildings.
Write largest_banner(heights).
heights is a list of whole numbers: the rooftop height of each building, in order along the street. A height can be 0, for an empty plot.Input: heights = [4, 7, 5, 5, 2, 6, 6, 6]
Output: 18Keep a stack of buildings whose heights rise from bottom to top. When a lower building arrives, every taller building on the stack stops growing to the right. Each one that is popped gives a banner: its height times the width back to the building under it on the stack.
| Building read | Height | Buildings popped (height × width) | Stack after |
|---|---|---|---|
| 0 | 4 | none | 0 |
| 1 | 7 | none | 0, 1 |
| 2 | 5 | building 1: 7 × 1 = 7 | 0, 2 |
| 3 | 5 | building 2: 5 × 2 = 10 | 0, 3 |
| 4 | 2 | building 3: 5 × 3 = 15; building 0: 4 × 4 = 16 | 4 |
| 5 | 6 | none | 4, 5 |
| 6 | 6 | building 5: 6 × 1 = 6 | 4, 6 |
| 7 | 6 | building 6: 6 × 2 = 12 | 4, 7 |
| end (height 0) | 0 | building 7: 6 × 3 = 18; building 4: 2 × 8 = 16 | empty |
The largest area is 18: height 6 across buildings 5, 6 and 7.
Input: heights = [3, 3, 3]
Output: 9The whole street is one banner of width 3 and height 3.
Input: heights = [0, 4, 0]
Output: 4The empty plots have height 0, so a banner over them has area 0. The best banner is the single building of height 4.
1 ≤ number of buildings ≤ 10^50 ≤ each height ≤ 10^4, so an area is at most 10^9 and fits in a 32-bit signed integerA plan that tries every first building and extends the banner to the right costs n × (n + 1) / 2 steps: about 5 × 10^9 for 100,000 buildings. That is too slow.
So the work must be close to n steps in all. Each building should be handled a constant number of times, and each banner counted, not tried.