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.
Input: ([1, 2, 3, 4, 5],)
Expected Output: 4
Explanation: Buy at 1 (day 0), sell at 5 (day 4); profit = 4.
Input: ([],)
Expected Output: 0
Explanation: Empty array: no transaction possible, return 0.
Input: ([5],)
Expected Output: 0
Explanation: Single day: cannot buy and sell on different days, return 0.
Input: ([2, 2, 2, 2],)
Expected Output: 0
Explanation: All prices equal, so no positive profit; return 0.
Input: ([3, 2, 6, 1, 4],)
Expected Output: 4
Explanation: Best is buy at 2 (day 1), sell at 6 (day 2); profit = 4. The later 1->4 only gives 3.
Input: ([2, 4, 1],)
Expected Output: 2
Explanation: Buy at 2 (day 0), sell at 4 (day 1); profit = 2. The trailing 1 cannot be sold higher.
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.