Definition
Largest value
Return the greatest element in a list of numbers.
Finding the maximum in an unsorted list is a single left-to-right scan: start with arr[0], then update whenever a larger value appears. This tutorial covers the pattern, empty-list handling, negatives, a live preview, worked Python examples, edge cases, and complexity.
Largest value
Return the greatest element in a list of numbers.
One pass
Track a running maximum while walking the list.
arr[0] first
Seed max_val with the first element, then compare the rest.
No max
Reject empty lists before scanning.
Sample → 42
Run the classic sample list in the browser.
O(1) space
One pass, constant extra memory — faster than sorting.
Finding the maximum in an unsorted list 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 lists — 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 > max_val.
Avoid sentinel values that break negatives.
Raise or validate before indexing.
Do not sort when you only need the max.
In short: if the list is non-empty, set max_val = arr[0], then for each later value update when larger.
Given a non-empty list of integers, return the largest value using one linear scan.
# [14, 7, 25, 31, 10, 42] -> 42
# max_val starts at 14, then updates to 25, 31, 42 | Item | Type | Description |
|---|---|---|
arr | list[int] | Non-empty list of numbers. |
| Return / print | int / text | The largest value in the list. |
function find_max(arr):
if arr is empty:
error
max_val <- arr[0]
for each value in arr from second element:
if value > max_val:
max_val <- value
return max_val | Method | Idea | Notes |
|---|---|---|
| Linear scan | Running maximum | Interview default — O(n), O(1) space |
Built-in max | 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 | max_val = arr[0] |
| Update | if arr[i] > max_val: max_val = arr[i] |
| Empty guard | if not arr: raise ValueError(...) |
| Slice loop | for x in arr[1:]: |
| Track index | Keep max_i when updating |
| Built-in | max(arr) (after explaining the scan) |
Same answer — different costs and interview signals.
running maxThis page — clear O(n) interview style
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-list 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 list as Example 1: 14, 7, 25, 31, 10, 42.
Three complete Python programs — classic scan to 42, all-negative list, 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 list with answer 42.
def find_max(arr: list[int]) -> int:
if not arr:
raise ValueError("Array must contain at least one element.")
max_val = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
return max_val
def main() -> None:
array = [14, 7, 25, 31, 10, 42]
max_value = find_max(array)
print(f"Maximum value in the array: {max_value}")
if __name__ == "__main__":
main() The function raises a clear error for empty input and uses one simple pass for normal lists. 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.
def find_max(arr: list[int]) -> int:
if not arr:
raise ValueError("Array must contain at least one element.")
max_val = arr[0]
for x in arr[1:]:
if x > max_val:
max_val = x
return max_val
def main() -> None:
negatives = [-9, -3, -1, -7]
print(f"Maximum (least negative): {find_max(negatives)}")
if __name__ == "__main__":
main() 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.
def find_max_with_index(arr: list[int]) -> tuple[int, int]:
if not arr:
raise ValueError("Array must contain at least one element.")
max_val = arr[0]
max_i = 0
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
max_i = i
return max_val, max_i
array = [14, 7, 25, 31, 10, 42]
value, index = find_max_with_index(array)
print(f"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 list is empty, raise an error — no maximum exists.
Set max_val = arr[0] as the first candidate.
For each later element, replace max_val when larger.
Return the final running maximum.
Trace the running maximum for [14, 7, 25, 31, 10, 42].
| Step | See | max_val |
|---|---|---|
| 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 list maximum shows up beyond the interview prompt.
One-pass loops and empty-list talk.
Example: write find_max(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 list and watch max_val update.
Seeding with arr[0] works for all-negative lists.
Track index, or flip to minimum with one change.
Pro Tip: lead with the manual scan; mention 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 list is empty.
→ Guard with if not arr first.
Using max_val = 0 on all-negative lists.
→ 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 (or use arr[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.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 lists, 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 max_val = arr[0], update when x > max_val.
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 list needs at least n - 1 comparisons in the worst case. A single left-to-right scan gives 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