Maximize one stock trade profit
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates algorithm design skills for single-pass array processing, streaming data handling, and time/space complexity analysis within the Coding & Algorithms domain.
Constraints
- 1 <= n <= 100000
- 0 <= prices[i] <= 1e9
- Required: O(n) time and O(1) extra space
- Buy must occur strictly before the sell day
Examples
Input: [7, 1, 5, 3, 6, 4]
Expected Output: 5
Explanation: Buy at 1 (day 1), sell at 6 (day 4): profit 5.
Input: [7, 6, 4, 3, 1]
Expected Output: 0
Explanation: Strictly decreasing prices; no profitable trade, so 0.
Hints
- You only need the lowest price seen so far to evaluate any potential sale today.
- For each day, the best profit ending today is current_price minus the minimum price before it.
- Track two running values in one pass: the minimum price so far and the maximum profit so far.
- If prices never rise above an earlier value, the answer is 0 (make no trade).