How to read a problem
Most wrong solutions come from solving the wrong problem. Before code, spend two minutes pinning down exactly what goes in, what comes out, and what happens at the edges. Interviewers watch for this step; it is also what separates a ticket you finish from one you redo.
- 1Restate it in one sentence
"Given an array of daily prices, return the maximum profit from one buy followed by one later sell." If you cannot say it, you cannot code it.
- 2Pin the contract
Input: array of numbers, length 0…10⁵, prices ≥ 0. Output: number ≥ 0; 0 if no profit is possible. Empty → 0.
- 3Work a tiny example by hand
[7, 1, 5, 3, 6, 4]→ buy at 1, sell at 6 → 5. Now you have a test. - 4List the edge cases
Empty; one price; always falling (
[5, 4, 3]→ 0); all equal; the best buy is the last day. - 5Say the brute force out loud
"Try every buy day and every later sell day" — O(n²). Correct first, fast second. Then ask what work is repeated.
You should see
ok [7,1,5,3,6,4] → 5
ok [] → 0
ok [5] → 0
ok [5,4,3] → 0
ok [2,2,2] → 0
ok [3,1,10] → 9