leet++Best Time to Buy and Sell Stock
EasyArrayGreedy

Best Time to Buy and Sell Stock

Given daily prices for one asset, choose one day to buy and a later day to sell. Return the largest positive gain, or zero if no profitable trade is possible.

Examples

Input: prices = [9, 4, 8, 2, 10]

Output: 8

Buying at 2 and selling later at 10 gives a gain of 8.

Input: prices = [11, 7, 5, 3]

Output: 0

Every later price is lower than the earlier prices.

Constraints & goals

  • There is at least one recorded day.
  • The buy day must come before the sell day.
  • Prefer a single left-to-right pass.

Camera feed

Preview
Camera starts when the session begins
Read-only

Transcribed whiteboard text will appear here.