Definition
Largest value
Return the greatest element in an 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 Java examples, edge cases, and complexity.
Largest value
Return the greatest element in an 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 for this task.
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, because the maximum is still the greatest 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.
Throw 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 | int[] | 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 |
| Library helper | stream().max() | 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 == 0) throw ... |
| Loop start | for (int i = 1; i < arr.length; i++) |
| Track index | Keep maxIndex when updating |
| Library helper | Arrays.stream(arr).max() after explaining the scan |
Same answer — different costs and interview signals.
running maxThis page — clear O(n) interview style
Arrays.stream(arr).max()Production shortcut after you can explain it
Arrays.sort(arr)Overkill — usually O(n log n)
mention emptyDefine behavior for empty arrays 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 the 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 Java 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 method and a sample array with answer 42.
public class FindMaxArray {
static int findMax(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array must contain at least one element.");
}
int maxVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
public static void main(String[] args) {
int[] array = { 14, 7, 25, 31, 10, 42 };
int maxValue = findMax(array);
System.out.println("Maximum value in the array: " + maxValue);
}
} The method throws 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.
public class FindMaxNegativeArray {
static int findMax(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array must contain at least one element.");
}
int maxVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
public static void main(String[] args) {
int[] negatives = { -9, -3, -1, -7 };
System.out.println("Maximum (least negative): " + findMax(negatives));
}
} Seeding with arr[0], not zero, is essential. Initializing to 0 would wrongly beat every negative value.
Common follow-up: return both the maximum and its first index.
Updates both value and index whenever a strictly larger element appears.
public class FindMaxWithIndex {
static int[] findMaxWithIndex(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array must contain at least one element.");
}
int maxVal = arr[0];
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
maxIndex = i;
}
}
return new int[] { maxVal, maxIndex };
}
public static void main(String[] args) {
int[] array = { 14, 7, 25, 31, 10, 42 };
int[] result = findMaxWithIndex(array);
System.out.println("Maximum " + result[0] + " found at index " + result[1]);
}
} 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, throw an error because 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 an 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 in interviews.
Example: n-1 comparisons lower bound.
Return the 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 comparison change.
Pro Tip: lead with the manual scan; mention library helpers only as a production aside.
Small habits that keep max-finding solutions interview-ready.
Throw 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 (arr.length == 0) 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.
→ Loop from index 1 after seeding the maximum.
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, such as -1.
Value is unchanged; index depends on > vs >=.
Same scan, no special case needed.
Use long[] if values may exceed int range.
Handy follow-ups interviewers sometimes ask.
< instead of >.Try these variations to lock in the pattern.
{14, 7, 25, 31, 10, 42}findMax(new int[0])O(n) time, O(1) extra space.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) |
| Library helper | 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 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