☰ All problems

10. Best Time to Buy and Sell Stock

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

You may make one trade: buy a single share on one day and sell it on a later day. Return the largest profit you can make. If no trade makes money, return 0.

Example 1
Input: prices = [8,3,6,2,7,4]
Output: 5

Explanation: Buy on day 3 at price 2 and sell on day 4 at price 7.

Example 2
Input: prices = [9,7,4,1]
Output: 0

Explanation: The price only falls, so the best choice is not to trade.

Example 3
Input: prices = [5,1,10,0,8]
Output: 9

Explanation: Buying at 0 gives at most 8; buying at 1 and selling at 10 earns more.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
💡 Hint 1

Checking every buy/sell pair is O(n²). If you decide to sell on day i, which buy day is best?

💡 Hint 2

The best buy day for selling on day i is the cheapest day before it. Track that running minimum as you scan.

/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc