The idea
Remember the extremes so far
You cannot know the maximum until you have looked at every element — but you can keep a running best guess.
Seed max_val and min_val with arr[0], then from index 1 onward compare and update.
TipStarting from the first element avoids needing a fake “infinity” starter value.
IdeaRunning extremes
max_min.pyPython
max_val = arr[0] min_val = arr[0] for i in range(1, len(arr)): if arr[i] > max_val: max_val = arr[i] if arr[i] < min_val: min_val = arr[i]
Array: [5, 2, 9, 1, 7] · Max 9 · Min 1
Interactive
Run the simulation
Boxes track i, max_val, and min_val as the scan proceeds.
demo.pyPython
Array + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember
One pass, two answers
You can track max and min together without a second loop.
Seed
Start with arr[0]
That gives both boxes a real value before the loop at index 1.
Compare
Update only when better
Greater than max → new max. Less than min → new min.
O(n)
Single scan
Every element is checked once — efficient and easy to follow.