CodePark/ problems / Best Day to Buy and Sell
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Sliding window

Best Day to Buy and Sell

easyabout 12 minutes in an interview

Each number in prices is a share price, one per day: prices[i] is the price on day i. You get at most one trade: buy a single share, then sell it on some day after you bought it. Return the biggest profit that trade can give, where profit is the sell price minus the buy price.

  • Buying and selling happen on different days, and selling comes second.
  • If no trade would gain anything, return 0. Skipping the trade is best then.
  • prices has up to 100,000 non-negative numbers. It may be empty.
Input: prices = [8, 3, 6, 1, 5, 2] Output: 4Buy at 1 on day 3, sell at 5 on day 4.
Input: prices = [9, 7, 4, 1] Output: 0The price only falls.