Optimal Stock TradingLoading saved progress…

Optimal Stock Trading

You are given an array prices where prices[i] is the price of a stock on day i. You may buy the stock on one day and sell it on a later day. Implement optimalStockTrading(prices) to return the maximum profit you can make from a single buy followed by a single sell. You must buy before you sell, so the sell day is strictly after the buy day. If no profitable trade exists, return 0. This is the classic Best Time to Buy and Sell Stock problem.

Signature

// prices: number[]   — prices[i] is the stock price on day i.
// returns: number     — the largest (sellPrice − buyPrice) where the buy day
//                       comes strictly before the sell day, or 0 if every
//                       such difference is negative or no trade is possible.
function optimalStockTrading(prices): number;

Examples

// Buy at 1 (day 1), sell at 6 (day 4) → profit 5.
optimalStockTrading([7, 1, 5, 3, 6, 4]);
// → 5
// Prices only fall, so no buy-then-sell makes money.
optimalStockTrading([7, 6, 4, 3, 1]);
// → 0

Notes

  • You buy before you sell. The sell day must come after the buy day. A single price gives you nothing to sell into, so it returns 0.
  • No profitable trade returns 0. If every later price is below the price you bought at, the best you can do is not trade. Never return a negative number.
  • The best sell is not always the global maximum. For [3, 2, 6, 1, 4] the cheapest day is 1, but the best trade is buy 2 then sell 6 for a profit of 4 — the global high 6 comes before the global low 1.
  • Empty input returns 0. optimalStockTrading([]) has no days to trade on.
  • One pass is enough. You do not need to compare every pair of days; aim for a single walk through the array.
Loading editor…