0

Linear scan with running state

Patternsused in ~100% of apps

This is the first real pattern, and it is the one you will use more than any other. Most problems that sound complicated are one walk through the list, carrying a small amount of information as you go.

Core idea. Walk the list once. Carry a few variables that remember what matters so far. Update them at each item. The answer is whatever those variables hold at the end.
Playground, this isn't a screenshot
what you carry decides the problem you can solve
sumWhat do they add up to?
sum = sum + x
bestWhat is the largest?
if (x > best) best = x
best, bestIndexWhere is the largest?
if (x > best) { best = x; bestIndex = i; }
countHow many are even?
if (x % 2 === 0) count++
run, bestRunLongest streak of increases?
run++ or run = 1; bestRun = max(...)
minSoFar, bestGainBest profit buying then selling?
bestGain = max(bestGain, x - minSoFar)

Same walk every time. Only the thing you carry changes.

↑ play a little first, then dig in