Skip to the code
cf.
+10 XP

#552 One Trade on a Price Chart

easy

A finance dashboard shows daily prices of one stock in prices. You may buy one share on one day and sell it on a later day, at most once.

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

Example 1

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

Buy at 2 and sell at 6, or buy at 1 and sell at 5.

Example 2

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

Prices only fall, so it is best not to trade.

Constraints

  • 1 <= prices.length <= 100000
  • 0 <= prices[i] <= 10000
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).