Closest Earlier Bid — Ordered Set / TreeMap
For each incoming bid, report its gap to the closest prior bid, using a placeholder for the first arrival.
Ordered Set / TreeMap · Easy
The problem
Bids arrive one at a time and no two bids are equal. For every bid, report how far it is from the closest bid that arrived before it, where the distance is the absolute difference of the two amounts. The first bid has no earlier bid, so report -1 for it.
The story
An auction site receives 1 to 300 bids, one after another, each a different whole-number amount from 1 to 100000. As each bid arrives, the site shows how far it is from the nearest earlier bid, higher or lower. The very first bid has nothing to compare with, so the site shows -1 for it. Report what the site shows for every bid, in order.
What to return
- Return a list with one entry per bid: the smallest absolute difference between that bid and any earlier bid.
- The entry for the first bid is -1.
- Large hidden tests (up to 300 bids) run under a step budget of executed lines.
Constraints
- 1 <= bids.length <= 300
- 1 <= bids[i] <= 100000
- all bids are different
- Your code may run at most 34,896 counted steps on the largest case.
Example
- Input
bids = [10, 4, 20, 12]- Output
[-1, 6, 10, 2]