Skip to the code
cf.
+10 XP

#61 Best Single Trade Window

easy

A trading widget shows a stock's closing price for each day in prices. You may buy once and sell once, on a later day.

Write bestTrade(prices) that returns the largest profit you can make. If no trade makes money, return 0.

Example 1

Input: prices = [9,4,6,2,8,5]
Output: 6

Buy at 2 on day 3 and sell at 8 on day 4.

Example 2

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

The price only falls, so don't trade.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).