Skip to main content
Back to problems
#2034
Medium Algorithms

Stock price fluctuation

Hash Table Design Heap (Priority Queue) Data Stream Ordered Set
48.9% acceptance
Feb 25, 2026
1277
70
Design an algorithm to track stock prices with the ability to update prices (corrections), find the latest price, max price, and min price. StockPrice() - initializes empty object update(timestamp, price) - updates price at timestamp current() - returns latest price maximum() - returns max price minimum() - returns min price

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::collections::{BTreeMap, HashMap};

pub struct StockPrice {
  prices: HashMap<i32, i32>,
  price_counts: BTreeMap<i32, i32>,
  latest_ts: i32,
}

impl StockPrice {
  pub fn new() -> Self {
    StockPrice {
      prices: HashMap::new(),
      price_counts: BTreeMap::new(),
      latest_ts: 0,
    }
  }

  pub fn update(&mut self, timestamp: i32, price: i32) {
    if let Some(&old_price) = self.prices.get(&timestamp) {
      let cnt = self.price_counts.get_mut(&old_price).unwrap();
      *cnt -= 1;
      if *cnt == 0 { self.price_counts.remove(&old_price); }
    }
    self.prices.insert(timestamp, price);
    *self.price_counts.entry(price).or_insert(0) += 1;
    if timestamp >= self.latest_ts {
      self.latest_ts = timestamp;
    }
  }

  pub fn current(&self) -> i32 {
    *self.prices.get(&self.latest_ts).unwrap()
  }

  pub fn maximum(&self) -> i32 {
    *self.price_counts.keys().next_back().unwrap()
  }

  pub fn minimum(&self) -> i32 {
    *self.price_counts.keys().next().unwrap()
  }
}