Definition
Largest value
Return the greatest element in a array of numbers.
Finding the maximum in an unsorted array is a single left-to-right scan: start with arr[0], then update whenever a larger value appears. This tutorial covers the pattern, empty-array handling, negatives, a live preview, worked JavaScript examples, edge cases, and complexity.
Largest value
Return the greatest element in a array of numbers.
One pass
Track a running maximum while walking the array.
arr[0] first
Seed maxVal with the first element, then compare the rest.
No max
Reject empty arrays before scanning.
Sample → 42
Run the classic sample array in the browser.
O(1) space
One pass, constant extra memory — faster than sorting.
Finding the maximum in an unsorted array means returning the largest value. Start with the first element as the current maximum; whenever you see a larger number, update it.
After one pass, the running maximum is the answer. The same idea works for all-negative arrays — the maximum is simply the greatest (least negative) value.
It is a classic interview warm-up that tests loops, comparisons, and empty-input thinking — and it mirrors finding the minimum.
Update whenever x > maxVal.
Avoid sentinel values that break negatives.
Raise or validate before indexing.
Do not sort when you only need the max.
In short: if the array is non-empty, set maxVal = arr[0], then for each later value update when larger.
Given a non-empty array of integers, return the largest value using one linear scan.
// [14, 7, 25, 31, 10, 42] -> 42
// maxVal starts at 14, then updates to 25, 31, 42 | Item | Type | Description |
|---|---|---|
arr | number[] | Non-empty array of numbers. |
| Return / print | int / text | The largest value in the array. |
function findMax(arr):
if arr is empty:
error
maxVal <- arr[0]
for each value in arr from second element:
if value > maxVal:
maxVal <- value
return maxVal | Method | Idea | Notes |
|---|---|---|
| Linear scan | Running maximum | Interview default — O(n), O(1) space |
Built-in max | Math.max(...arr) | Fine in apps; show loops in interviews |
| Sort then take last | Sort ascending | Slower — avoid when only max is needed |
| Goal | Pattern |
|---|---|
| Seed | maxVal = arr[0] |
| Update | if arr[i] > maxVal: maxVal = arr[i] |
| Empty guard | if (!arr.length) throw new Error(...) |
| Slice loop | for (let i = 1; i < arr.length; i++) |
| Track index | Keep maxI when updating |
| Built-in | Math.max(...arr) (after explaining the scan) |
Same answer — different costs and interview signals.
running maxThis page — clear O(n) interview style
Math.max(...arr)Production shortcut after you can explain it
sorted(arr)[-1]Overkill — usually O(n log n)
mention emptyDefine behavior for [] up front
Reach for a running maximum whenever you need the largest value in one pass.
Loops, comparisons, and empty-array discussion.
Same pattern; next page flips the comparison.
Highest score, peak temperature, top sale.
Practice greater-than updates and negatives.
If you need order of all elements, sort instead.
Key benefit: one short loop that locks in running state, empty guards, and O(n) reasoning.
Uses the same sample array as Example 1: 14, 7, 25, 31, 10, 42.
Three complete JavaScript programs — classic scan to 42, all-negative array, and max-with-index tracking. Click View Output to reveal sample console results.
A reusable helper and a mixed positive sample.
A reusable helper function and a sample array with answer 42.
function findMax(arr) {
if (!arr.length) {
throw new Error("Array must contain at least one element.");
}
let maxVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
const array = [14, 7, 25, 31, 10, 42];
const maxValue = findMax(array);
console.log(`Maximum value in the array: ${maxValue}`); The function raises a clear error for empty input and uses one simple pass for normal arrays. Running max starts at 14, then updates to 25, 31, and finally 42.
The maximum is the greatest value — even when every element is negative.
The same algorithm still works; maximum is the least negative value.
function findMax(arr) {
if (!arr.length) {
throw new Error("Array must contain at least one element.");
}
let maxVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
const negatives = [-9, -3, -1, -7];
console.log(`Maximum (least negative): ${findMax(negatives)}`); Seeding with arr[0] (not zero) is essential — initializing to 0 would wrongly beat every negative. Here -1 is greater than -3, -7, and -9.
Common follow-up: return both the maximum and its first index.
Updates both value and index whenever a strictly larger element appears.
function findMaxWithIndex(arr) {
if (!arr.length) {
throw new Error("Array must contain at least one element.");
}
let maxVal = arr[0];
let maxI = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
maxI = i;
}
}
return { value: maxVal, index: maxI };
}
const array = [14, 7, 25, 31, 10, 42];
const { value, index } = findMaxWithIndex(array);
console.log(`Maximum ${value} found at index ${index}`); Strict > keeps the first occurrence if duplicates exist. Use >= only if you intentionally want the last index of the maximum.
If the array is empty, raise an error — no maximum exists.
Set maxVal = arr[0] as the first candidate.
For each later element, replace maxVal when larger.
Return the final running maximum.
Trace the running maximum for [14, 7, 25, 31, 10, 42].
| Step | See | maxVal |
|---|---|---|
| Start | 14 | 14 |
| Next | 7 | 14 (unchanged) |
| Next | 25 | 25 |
| Next | 31 | 31 |
| Next | 10 | 31 (unchanged) |
| Next | 42 | 42 |
Final answer: 42 — matching Example 1.
Where finding a array maximum shows up beyond the interview prompt.
One-pass loops and empty-array talk.
Example: write findMax(arr).
Same scan; next page flips the comparison.
Example: swap > for <.
Highest score or peak reading in a series.
Example: max temperature today.
Show why seeding with arr[0] beats using 0.
Example: max of [-9, -1].
State O(n) vs sorting for interviews.
Example: n-1 comparisons lower bound.
Return position of the maximum too.
Example: Example 3 pattern.
Pro Tip: open with “empty check, seed arr[0], one pass with >” before writing code.
Why the linear-scan approach works well in interviews.
O(n) time and O(1) extra space for unsorted input.
Dry-run a short array and watch maxVal update.
Seeding with arr[0] works for all-negative arrays.
Track index, or flip to minimum with one change.
Pro Tip: lead with the manual scan; mention Math.max(...arr) only as a production aside.
Small habits that keep max-finding solutions interview-ready.
Raise before reading arr[0].
Do not initialize to 0 when negatives are possible.
Keeps the first index if you also track position.
Sorting is slower when you only need the max.
One pass, constant extra memory.
Pro Tip: dry-run 14 → 25 → 31 → 42 aloud — if that matches, your update logic is correct.
Mistakes that commonly break max-finding solutions.
Reading arr[0] when the array is empty.
→ Guard with if not arr first.
Using maxVal = 0 on all-negative arrays.
→ Seed with arr[0] instead.
Sorting just to take the last element.
→ Use one O(n) scan.
Starting the loop at 0 and comparing arr[0] to itself only.
→ Loop from index 1 with for (let i = 1; ...).
Copying max code but forgetting to flip > to <.
→ Minimum uses the opposite comparison.
Handle these before claiming the scan is complete.
No maximum exists; handle this before scanning.
That element is automatically the maximum.
Maximum is the least negative value (e.g. -1).
Value is unchanged; index depends on > vs >=.
Same scan — no special case needed.
Same comparison logic works for floats.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
O(n) time, O(1) extra space.Math.max(...arr), but interviewers often ask for the manual scan first. Huge data can combine partial maxima in parallel.Quick Takeaway: guard empty, seed with arr[0], update on >, return in O(n) time.
| Approach | Time | Extra space |
|---|---|---|
| Single scan | O(n) | O(1) |
Built-in max | O(n) | O(1) |
| Sort then take last | O(n log n) | depends on sort |
For unsorted input, a single scan is the standard interview answer.
Finding the maximum is a one-pass running maximum: guard empty arrays, seed with arr[0], and update on greater values. The same pattern works for negatives and extends cleanly to tracking the index.
Practice the three examples above, then continue to finding the minimum value of an array.
Empty check first, then maxVal = arr[0], update when x > maxVal.
arr[0]Find the largest value the interview-friendly way.
Running max
PatternStart at arr[0]
InitGuard first
SafetyStill works
EdgeO(n) / O(1)
AnalysisFinding the maximum in an unsorted array needs at least n − 1 comparisons in the worst case. A single left-to-right scan achieves O(n) time and O(1) extra space.
Learn the same one-pass pattern with the opposite comparison to find the smallest value.
8 people found this page helpful