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

Constraints

Example

Input
bids = [10, 4, 20, 12]
Output
[-1, 6, 10, 2]

Solve it

More in Ordered Set / TreeMap

All algorithm problems