How to read a problem
Most wrong answers come from solving the wrong problem. Before any code, write three lines: what comes in (type, size, can it be empty, can it have duplicates or negatives), what must come out (type, order, what if there is no answer), and one example you worked by hand. Interviewers grade this step; production bugs live in it.
- 1Restate it in one sentence
"Given a list of daily prices, return the maximum profit from one buy followed by one sell." If you cannot say it, you cannot code it.
- 2Pin the contract
Input: list of ints, length 0…10⁵, prices ≥ 0. Output: int ≥ 0; 0 if no profit possible. Empty list → 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