Best Time to Buy and Sell Stock
viaLeetCode
Problem Given prices where prices[i] is a stock's price on day i, maximize profit from one buy followed by one later sell; return 0 if no profitable trade exists.
Input / Output
- Input: int array prices. Output: max profit.
Constraints
- n up to 10^5; O(n) single pass expected.
Example
- [7,1,5,3,6,4] → 5 (buy at 1, sell at 6); [7,6,4,3,1] → 0.
Expected approach
- One pass tracking minSoFar and best = max(best, price − minSoFar). O(n)/O(1). Equivalent framing: max subarray (Kadane) over daily deltas — worth mentioning. Know the family: unlimited transactions (sum positive deltas), with cooldown/fee, and at-most-k transactions (DP) — interviewers often escalate through them.
asked …