Knew the answer pretty quickly but still fumbled the first explanation.
Start by clarifying the problem constraints and edge cases, then propose an efficient O(n) single-pass solution that tracks the minimum price seen so far and the maximum profit. Walk through a small example to demonstrate correctness and discuss time/space complexity.
Pro tip: Mention that this is a classic problem where a greedy approach works because the optimal sell day depends only on the minimum price before it. Also, explicitly handle edge cases like empty array or strictly decreasing prices to show thoroughness.
Confirm that you can buy and sell at most once, sell must be after buy, and return 0 if no profit. Ask about input size, data types, and whether the array can be empty or have one element.
Briefly mention the O(n^2) solution of checking all pairs to establish a baseline, then explain why it's inefficient for large inputs.
Describe tracking the minimum price seen so far and computing the profit if sold today, updating the maximum profit. This single pass yields the answer.
Use a small array like [7,1,5,3,6,4] to illustrate how the algorithm works step by step, showing the updates to min price and max profit.
State that time complexity is O(n) and space is O(1). Mention that this is optimal since you must examine each price at least once.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.