Largest value
Rules of thumbBestO(n)
AverageO(n)
WorstO(n)
Extra spaceO(1)
- Use it whenYou need one summary of a list (largest, smallest, total): one pass with a running variable.
- TipSay what your variable means after every step. If that stays true, the answer is right.
- TipIn real code call `max(values)`: the same algorithm, already written and tested.
- Watch outStarting with `best = 0` breaks on all-negative lists. Start from the first value.
- Avoid it whenSorting just to take the last value: a sort does far more work than one pass.
RememberOne pass, one running best: n values, n − 1 comparisons.