← DiffPush

Best Time to Buy and Sell Stock

Baseline Dynamic Programming · DP on Stocks O(n) · O(1)

The Single-Shuttle Freight Arbitrage

A logistics broker charters one shuttle between two depots whose transfer fee varies by the hour. The broker may lock a fee once (the buy) and release it later at a higher fee (the sell), strictly in that order. Dispatch wants the biggest spread achievable from exactly one lock-release cycle, or zero when every release would come out behind.

Input: An array prices where prices[i] is the fee on hour i.

Output: Return the maximum profit from one buy followed by one later sell, or 0 when no profitable pair exists.

Constraints

Examples

Example 1

Input: {"prices":[7,1,5,3,6,4]}
Output: 5
Lock at 1, release at 6 — spread 5.

Example 2

Input: {"prices":[7,6,4,3,1]}
Output: 0
Fees only fall, so no release ever beats its lock; the answer is 0.

Solve this in your browser →

Also on LeetCode ↗