CodingNodes / Sliding Window / Best Time to Buy And Sell Stock System design Space play · ←→ step · R restart

Problem

The array prices holds the price of one stock on each day, in order. You may pick one day to buy and a later day to sell.

Return the largest profit you can make. If every possible trade loses money, return 0 (you simply do not trade).

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over the days. Each day costs one comparison and one subtraction.

Space: Only two numbers are kept: the lowest price so far and the best profit so far.

Walk through the days once. Remember the lowest price seen so far. On each day, either it is a new lowest price, or it is a possible selling day, worth price − lowest.