Editor

Stock Price Tracker

#395 · Heaps · Advanced · 140 XP · about 30 min

A trading feed sends (timestamp, price) records for one stock. Records can arrive out of order, and a record for a timestamp that was already seen is a correction: it replaces the earlier price for that timestamp. Build a StockTracker class:

  • StockTracker() starts with no records.
  • update(timestamp, price) records the price at timestamp, or corrects it.
  • current() returns the price at the latest timestamp seen so far.
  • highest() returns the highest price over all timestamps, using the corrected prices.
  • lowest() returns the lowest price over all timestamps, using the corrected prices.

current, highest and lowest are only called after at least one update.

Examples

st = StockTracker()
st.update(1, 10)
st.update(2, 5)
st.current()     # returns 5
st.highest()     # returns 10
st.update(1, 3)  # the price at time 1 was wrong
st.highest()     # returns 5
st.lowest()      # returns 3
st.update(4, 2)
st.current()     # returns 2

Constraints

  • Up to 150,000 calls; timestamps and prices are whole numbers from 1 to 10^9
  • With 50,000 timestamps and tens of thousands of questions, looking at every timestamp for each highest or lowest is far too slow.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.