easyArrays & HashingPure DSA~13 min
Single Trade Profit
A pricing dashboard plots an asset's daily close. A simulator offers one buy and one later sell — report the maximum profit a single round trip could have captured, or zero if prices only fell.
Problem
Given an array prices where prices[i] is the price on day i, return the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.
Input
An array prices of length n (1 ≤ n ≤ 10^5), values in [0, 10^9].
Output
A single integer — the maximum achievable profit.
Constraints
- 1 ≤ n ≤ 100,000
- Sell day must be strictly after buy day
- Return 0 if prices are non-increasing
Examples
Example 1
Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Buy at 1 (day 1), sell at 6 (day 4): profit 5.
Example 2
Input
prices = [7, 6, 4, 3, 1]
Output
0
Prices only fall, so the best move is not to trade.