Facebook PixelBest Time to Buy and Sell Stock — Coding Practice
Best Time to Buy and Sell StockEasy

Best Time to Buy and Sell Stock

Easy 31.9k54% acceptance
ArrayDynamic Programming

You are given an array prices where prices[i] is the price of a stock on day i.

Choose one day to buy and a later day to sell to maximize profit. Return the maximum profit, or 0 if no profit is possible.

Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Buy on day 2 (price 1), sell on day 5 (price 6).
Example 2
Input: prices = [7,6,4,3,1]
Output: 0
Prices only fall — never buy.
Constraints
  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴
Asked atAmazonMetaGoogleMicrosoft
JavaScript
Loading editor…
Case 1
[7,1,5,3,6,4]
expected: 5
Case 2
[7,6,4,3,1]
expected: 0
Case 3
[2,4,1]
expected: 2
Case 4
[1]
expected: 0