← DiffPush

Stock buy sell

Standard Bar Arrays · Medium O(n) · O(1)

One Round Trip on the Trading Desk

A desk clerk has the daily closing prices for a commodity and may buy on one day and sell on a later day, exactly once. The rules forbid buying after the sale date, and if every later price is lower the clerk simply sits out. Compute the best profit available under those rules.

Input: An array prices of n integers, the closing price per day.

Output: The maximum achievable profit from one buy followed by one later sell, or 0 when no profit is possible.

Constraints

Examples

Example 1

Input: {"prices":[7,1,5,3,6,4]}
Output: 5
Buying at the day-2 price of 1 and selling at the day-5 price of 6 yields the best profit of 5.

Example 2

Input: {"prices":[7,6,4,3,1]}
Output: 0
Prices only fall, so every buy would lose money and the clerk sits out with profit 0.

Solve this in your browser →

Also on LeetCode ↗