466. Max Commodity Price
Max Commodity Price

Implement the RunningCommodityPrice class to process a stream of commodity prices. Each event provides a timestamp and a price. Events may arrive out of timestamp order.

Constructor

RunningCommodityPrice()
  • Creates an object with no price records.

Methods

Add or Update a Price

void upsertCommodityPrice(int timestamp, int commodityPrice)
  • timestamp: The timestamp of the price record.
  • commodityPrice: The price to store at that timestamp.
  • Add a record if the timestamp is new. Otherwise, replace its previous price with commodityPrice.
  • Each timestamp stores only the price from its most recently received event.

Get the Maximum Price

int getMaxCommodityPrice()
  • Return the largest price among all currently stored timestamp records.
  • Ignore prices that have been replaced. Updating a record may increase or decrease the maximum.

Constraints

  • 0 ≤ timestamp ≤ 1,000,000,000
  • 0 ≤ commodityPrice ≤ 1,000,000,000
  • At most 100,000 method calls are made per object.
  • getMaxCommodityPrice() is called only after at least one call to upsertCommodityPrice.

Examples

Each example starts with a new object. Parameter names in the calls are labels for readability.

Example 1: Out-of-Order Events and a Lowered Maximum

  1. RunningCommodityPrice r = new RunningCommodityPrice();
  2. r.upsertCommodityPrice(timestamp = 14, commodityPrice = 70);
  3. r.upsertCommodityPrice(timestamp = 3, commodityPrice = 55);
  4. r.upsertCommodityPrice(timestamp = 9, commodityPrice = 62);
  5. r.getMaxCommodityPrice(); Output: 70.
  6. r.upsertCommodityPrice(timestamp = 14, commodityPrice = 40);
  7. r.getMaxCommodityPrice(); Output: 62.

The price at timestamp 14 changes from 70 to 40. The maximum is now 62, stored at timestamp 9.

Example 2: Equal Prices and Repeated Updates

  1. RunningCommodityPrice r = new RunningCommodityPrice();
  2. r.upsertCommodityPrice(timestamp = 8, commodityPrice = 36);
  3. r.upsertCommodityPrice(timestamp = 2, commodityPrice = 36);
  4. r.getMaxCommodityPrice(); Output: 36.
  5. r.upsertCommodityPrice(timestamp = 8, commodityPrice = 21);
  6. r.getMaxCommodityPrice(); Output: 36.
  7. r.upsertCommodityPrice(timestamp = 2, commodityPrice = 50);
  8. r.getMaxCommodityPrice(); Output: 50.

Lowering the price at timestamp 8 leaves the maximum unchanged because timestamp 2 still stores 36. Updating timestamp 2 to 50 raises the maximum.



Please use Laptop/Desktop or any other large screen to add/edit code.