I knew this one but still fumbled the explanation a bit.
Clarify the problem constraints (single transaction, return 0 if no profit) and then describe a one-pass algorithm that tracks the minimum price seen so far and the maximum profit. Emphasize that this achieves O(n) time and O(1) space by updating these two variables in a single iteration.
Pro tip: Mention that you would handle edge cases like an empty array or strictly decreasing prices by returning 0, and note that the algorithm works even if the best transaction is to not buy at all.
Confirm that only one buy and one sell are allowed, that the buy must occur before the sell, and that if no profit is possible, return 0.
Recognize that the maximum profit ending at day i is either the profit from selling at day i (price[i] - min_price_so_far) or the maximum profit from previous days.
Initialize min_price to infinity and max_profit to 0. Iterate through the array, updating min_price and then max_profit with the maximum of its current value and price - min_price.
State that the algorithm runs in O(n) time because it makes a single pass, and uses O(1) extra space for the two variables.
Walk through a few test cases, including increasing prices, decreasing prices, and a mix, to verify correctness and edge cases.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.