I knew this problem cold, or thought I did.
Clarify the problem constraints and edge cases, then present the single-pass greedy algorithm that tracks the minimum price seen so far and the maximum profit. Explain the algorithm step-by-step, prove its correctness using an invariant, and analyze time and space complexity. If time permits, extend to return the buy and sell indices.
Pro tip: Emphasize that the algorithm is optimal and handles all edge cases, including decreasing prices and single-element arrays. Mention that the same pattern applies to similar problems like 'Best Time to Buy and Sell Stock II' but with modifications.
Confirm that the array represents daily prices, buy must precede sell, and only one transaction is allowed. Discuss edge cases: empty array, single day, strictly decreasing prices, and all equal prices.
Describe the single-pass approach: initialize min_price to infinity and max_profit to 0. Iterate through prices, update min_price if current price is lower, else compute profit if sold today and update max_profit if higher.
Use an invariant: after processing day i, min_price is the minimum price in days 0..i, and max_profit is the maximum profit achievable with a transaction ending by day i. Show that the algorithm maintains this invariant and yields the correct result.
State that the algorithm runs in O(n) time because it makes a single pass, and O(1) space because it uses only a few variables. Compare with brute-force O(n^2) to highlight efficiency.
Modify the algorithm to record the buy day when updating min_price and the sell day when updating max_profit. Return the indices along with the profit.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.