Compute max profit from single stock trade
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to design efficient array algorithms, reason about time and space complexity constraints, and handle edge cases related to single-transaction profit calculation.
Constraints
- 0 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
- You may complete at most one transaction (one buy followed by one later sell).
- If no profitable transaction exists, return 0.
Examples
Input: ([7, 1, 5, 3, 6, 4],)
Expected Output: 5
Explanation: Buy at 1 (day 1), sell at 6 (day 4); profit = 5, the maximum achievable.
Input: ([7, 6, 4, 3, 1],)
Expected Output: 0
Explanation: Prices strictly decrease, so any buy-then-sell loses money; return 0.
Hints
- Track the lowest price seen so far as you scan left to right; the best sell-on-day-i profit is prices[i] minus that running minimum.
- Keep two running values: the minimum price so far and the maximum profit so far. Update profit before lowering the minimum, since you must buy strictly before you sell.
- Brute force tries every (buy, sell) pair in O(n^2); the single-pass approach collapses this to O(n) time and O(1) space.