Ad platform~12 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
An ad platform sells one banner slot. It sets the slot's price from the bids it received, using the second highest distinct bid. Equal bids from different advertisers count once.
If the bids hold fewer than two different amounts, the slot has no price. Bids are whole units, and the list can be empty.
Write second_highest_bid(bids).
bids[i] is the amount of one bid, in units.-1 when there are fewer than two different amounts.Input: bids = [30, 80, 50, 80, 20]
Output: 50Keep the highest and the second highest amount seen so far. Start both at -1.
| Bid | Highest | Second highest |
|---|---|---|
| 30 | 30 | -1 |
| 80 | 80 | 30 |
| 50 | 80 | 50 |
| 80 | 80 | 50 |
| 20 | 80 | 50 |
The second 80 equals the highest, so it changes nothing.
Input: bids = [40, 40, 40]
Output: -1Every bid is the same amount, so there is no second highest.
Input: bids = [9, 4]
Output: 4With two different amounts, the lower one is the second highest.
0 ≤ bids.length ≤ 100,000 (bids on one slot)1 ≤ bids[i] ≤ 1,000,000,000 (units)Checking every bid against every other bid costs about n × n steps, which is 10^10 at n = 100,000. The bids can be read once, so the work should be about n, and only two numbers need to be kept.