Ride-hailing app~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-716stacks · heaps
A driver app shows fare offers as they arrive, newest on top of a stack. The driver can drop the newest offer, look at it, look at the best offer, or accept the best offer.
Accepting the best offer removes it wherever it sits in the stack. If several offers are equally good, the newest of them is accepted. With 100,000 commands, scanning the stack for the best offer every time is too slow.
Write run_offers(commands, values).
values[i] is the fare of a push and is ignored by the other commands.push puts the fare on top and answers the number of offers now on the stack.pop removes the newest offer and answers its fare, or -1 if the stack is empty.top answers the fare of the newest offer without removing it, or -1 if the stack is empty.peekmax answers the largest fare on the stack without removing it, or -1 if the stack is empty.popmax removes the largest fare and answers it, or -1 if the stack is empty. Among equal largest fares it removes the newest.Input: commands = ["push", "push", "push", "push", "peekmax", "popmax", "top", "popmax", "pop", "pop", "popmax", "top"], values = [5, 9, 2, 9, 0, 0, 0, 0, 0, 0, 0, 0]
Output: [1, 2, 3, 4, 9, 9, 2, 9, 2, 5, -1, -1]The table lists the offers on the stack from the bottom to the top after each command.
| Command | Offers on the stack | Answer |
|---|---|---|
push 5 |
5 | 1 |
push 9 |
5, 9 | 2 |
push 2 |
5, 9, 2 | 3 |
push 9 |
5, 9, 2, 9 | 4 |
peekmax |
5, 9, 2, 9 | 9 |
popmax |
5, 9, 2 | 9 |
top |
5, 9, 2 | 2 |
popmax |
5, 2 | 9 |
pop |
5 | 2 |
pop |
(empty) | 5 |
popmax |
(empty) | -1 |
top |
(empty) | -1 |
The first popmax removed the newer 9, the one on top. The second removed the older 9, from under the 2.
Input: commands = ["push", "push", "popmax", "popmax", "top"], values = [7, 7, 0, 0, 0]
Output: [1, 2, 7, 7, -1]Both fares are 7. Either removal gives the same answer, and the stack ends empty.
Input: commands = ["pop", "top", "peekmax", "popmax", "push", "popmax"], values = [0, 0, 0, 0, 4, 0]
Output: [-1, -1, -1, -1, 1, 4]Every read of an empty stack answers -1. After the push, popmax takes the only offer.
1 ≤ len(commands) = len(values) ≤ 100,000push, pop, top, peekmax and popmax0 ≤ values[i] ≤ 10^6Scanning the stack for the largest fare costs the size of the stack. With 60,000 offers on the stack and 40,000 scans, that is about two billion steps.
A command must cost about 17 steps, the depth of a heap of 100,000 entries, so all commands together take a few million steps.