- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Array Traversal Patterns
Arrays
Array Traversal Patterns
Most array problems are one of four walks. Recognising which one you need is faster than inventing a solution from scratch.
1. Single pass with running state
Carry one value through the array and update it as you go. Works whenever the answer depends only on what you have already seen.
Running total and best run
javascript
function largest(items) {
let best = items[0]
for (const n of items) {
if (n > best) best = n
}
return best
}
// Largest sum of any run of consecutive numbers.
function bestRun(items) {
let best = items[0]
let current = items[0]
for (let i = 1; i < items.length; i++) {
current = Math.max(items[i], current + items[i])
best = Math.max(best, current)
}
return best
}
console.log(bestRun([-2, 1, -3, 4, -1, 2, 1, -5, 4])) // 6