CodingNodes / Arrays & Hashing / Best Time to Buy and Sell Stock II System design Space play · ←→ step · R restart

Problem

You are given prices, where prices[i] is a stock's price on day i.

You may buy and sell as many times as you like, but you can hold at most one share at a time. You may sell and buy again on the same day. Return the largest total profit you can make.

Constraints

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

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: A single pass over the prices.

Space: Only the running profit and the current gain are kept.

Any profitable plan is a set of climbs, and a climb from low to high equals the sum of its day-to-day rises. So add up every positive day-to-day change and ignore the drops. This is the best possible because every rise is taken and no drop is ever paid for.