Maximize one stock trade profit
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: 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.
Input: [1, 2, 3, 4, 5]
Expected Output: 4
Explanation: Buy at 1, sell at 5: profit 4.
Input: [5]
Expected Output: 0
Explanation: A single day leaves no later day to sell; profit 0.
Input: []
Expected Output: 0
Explanation: No prices, no transaction possible; profit 0.
Input: [2, 2, 2, 2]
Expected Output: 0
Explanation: All prices equal; max profit is 0.
Input: [3, 2, 6, 5, 0, 3]
Expected Output: 4
Explanation: Buy at 2 (day 1), sell at 6 (day 2): profit 4; the later dip to 0 then 3 only yields 3.
Input: [0, 1000000000]
Expected Output: 1000000000
Explanation: Boundary values: buy at 0, sell at 1e9: profit 1e9.
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).