Skip to problem
←

Best Time to Buy and Sell Stock

Easy 0 attempts

You're given an array prices, where prices[i] holds a stock's price on day i. You may complete at most one transaction: buy on one day and sell on a later day. You may also choose not to trade. Work out the largest profit achievable from this single buy-then-sell transaction, returning 0 if no profitable trade is possible.

Function contract

Implement maxProfit(prices), where prices[i] is the price on day i.

Output: The maximum profit from at most one buy followed by a sale on a later day. Return 0 if no profitable trade exists.

Example 1

Input
prices = [7,1,5,3,6,4]
Output
5

Explanation: Buy at 1 and later sell at 6 for a profit of 5.

Example 2

Input
prices = [7,6,4,3,1]
Output
0
Constraints
  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Track the minimum price seen so far as you iterate. At each step, compute the profit if you sold today and update the maximum profit accordingly.

javascript
function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;

  for (const price of prices) {
    minPrice = Math.min(minPrice, price);
    maxProfit = Math.max(maxProfit, price - minPrice);
  }

  return maxProfit;
}

Time: O(n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript