Find Maximum Value of an Array in Java

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

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.

Definition

Largest value

Return the greatest element in an array of numbers.

Linear Scan

One pass

Track a running maximum while walking the array.

Init Rule

arr[0] first

Seed maxVal with the first element, then compare the rest.

Empty Guard

No max

Reject empty arrays before scanning.

Live Preview

Sample → 42

Run the classic sample array in the browser.

O(n) Cost

O(1) space

One pass, constant extra memory, faster than sorting for this task.

Introduction

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.

Why it matters?

It is a classic interview warm-up that tests loops, comparisons, and empty-input thinking, and it mirrors finding the minimum.

Key Highlights

Running Max

Update whenever x > maxVal.

Seed With First

Avoid sentinel values that break negatives.

Empty Guard

Throw or validate before indexing.

Beat Sorting

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.

📝 Problem & Approach

Given a non-empty array of integers, return the largest value using one linear scan.

java
// [14, 7, 25, 31, 10, 42] -> 42
// maxVal starts at 14, then updates to 25, 31, 42

Inputs & Outputs

ItemTypeDescription
arrint[]Non-empty array of numbers.
Return / printint / textThe largest value in the array.

Minimal workflow

Pseudocode
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 comparison

MethodIdeaNotes
Linear scanRunning maximumInterview default — O(n), O(1) space
Library helperstream().max()Fine in apps; show loops in interviews
Sort then take lastSort ascendingSlower — avoid when only max is needed

⚡ Quick Reference

GoalPattern
SeedmaxVal = arr[0]
Updateif (arr[i] > maxVal) maxVal = arr[i];
Empty guardif (arr.length == 0) throw ...
Loop startfor (int i = 1; i < arr.length; i++)
Track indexKeep maxIndex when updating
Library helperArrays.stream(arr).max() after explaining the scan

📋 Scan vs Library vs Sort

Same answer — different costs and interview signals.

Linear scan
running max

This page — clear O(n) interview style

Library
Arrays.stream(arr).max()

Production shortcut after you can explain it

Sort
Arrays.sort(arr)

Overkill — usually O(n log n)

Interview tip
mention empty

Define behavior for empty arrays up front

Context

When This Problem Shows Up

Reach for a running maximum whenever you need the largest value in one pass.

  1. Interview warm-ups

    Loops, comparisons, and empty-array discussion.

  2. Before minimum

    Same pattern; next page flips the comparison.

  3. Scores and readings

    Highest score, peak temperature, top sale.

  4. Teaching comparisons

    Practice greater-than updates and negatives.

  5. Not for sorting needs

    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.

🔮 Live Preview

Uses the same sample array as Example 1: 14, 7, 25, 31, 10, 42.

Runs the same linear-scan logic in JavaScript.

Live result
Press “Find maximum”.

Examples Gallery

Three complete Java programs: classic scan to 42, all-negative array, and max-with-index tracking. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and a mixed positive sample.

Example 1 — Find Maximum (Reference Program)

A reusable helper method and a sample array with answer 42.

java
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);
    }
}

How It Works

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.

⚡ Negatives Still Work

The maximum is the greatest value, even when every element is negative.

Example 2 — When Every Element Is Negative

The same algorithm still works; maximum is the least negative value.

java
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));
    }
}

How It Works

Seeding with arr[0], not zero, is essential. Initializing to 0 would wrongly beat every negative value.

⚙️ Track Position Too

Common follow-up: return both the maximum and its first index.

Example 3 — Maximum With Index

Updates both value and index whenever a strictly larger element appears.

java
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]);
    }
}

How It Works

Strict > keeps the first occurrence if duplicates exist. Use >= only if you intentionally want the last index of the maximum.

🧠 How the Algorithm Finds the Max

1

Guard empty

If the array is empty, throw an error because no maximum exists.

Safety
2

Seed maxVal

Set maxVal = arr[0] as the first candidate.

Init
3

Scan and update

For each later element, replace maxVal when larger.

Loop
=

Maximum ready

Return the final running maximum.

🔎 Worked Walkthrough — Sample Array

Trace the running maximum for [14, 7, 25, 31, 10, 42].

StepSeemaxVal
Start1414
Next714 (unchanged)
Next2525
Next3131
Next1031 (unchanged)
Next4242

Final answer: 42 — matching Example 1.

Use Cases

Where finding an array maximum shows up beyond the interview prompt.

1. Interview Warm-Ups

One-pass loops and empty-array talk.

Example: write findMax(arr).

2. Before Minimum

Same scan; next page flips the comparison.

Example: swap > for <.

3. Scores & Peaks

Highest score or peak reading in a series.

Example: max temperature today.

4. Negatives Practice

Show why seeding with arr[0] beats using 0.

Example: max of { -9, -1 }.

5. Complexity Talk

State O(n) vs sorting in interviews.

Example: n-1 comparisons lower bound.

6. Index Follow-Ups

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.

Advantages

Why the linear-scan approach works well in interviews.

  1. 1. Optimal Simple Cost

    O(n) time and O(1) extra space for unsorted input.

  2. 2. Easy to Trace

    Dry-run a short array and watch maxVal update.

  3. 3. Handles Negatives

    Seeding with arr[0] works for all-negative arrays.

  4. 4. Easy to Extend

    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.

Usage Tips

Small habits that keep max-finding solutions interview-ready.

  1. 1. Guard Empty First

    Throw before reading arr[0].

  2. 2. Seed With arr[0]

    Do not initialize to 0 when negatives are possible.

  3. 3. Prefer Strict >

    Keeps the first index if you also track position.

  4. 4. Skip Sorting

    Sorting is slower when you only need the max.

  5. 5. State O(n) / O(1)

    One pass, constant extra memory.

Pro Tip: dry-run 14 → 25 → 31 → 42 aloud — if that matches, your update logic is correct.

Common Pitfalls

Mistakes that commonly break max-finding solutions.

  1. 1. Empty Array Crash

    Reading arr[0] when the array is empty.

    → Guard with if (arr.length == 0) first.

  2. 2. Initializing to Zero

    Using maxVal = 0 on all-negative arrays.

    → Seed with arr[0] instead.

  3. 3. Sorting Unnecessarily

    Sorting just to take the last element.

    → Use one O(n) scan.

  4. 4. Off-by-One Loop

    Starting the loop at 0 and comparing arr[0] to itself.

    → Loop from index 1 after seeding the maximum.

  5. 5. Wrong Comparison for Min

    Copying max code but forgetting to flip > to <.

    → Minimum uses the opposite comparison.

Edge Cases

Handle these before claiming the scan is complete.

Empty

Empty array

No maximum exists; handle this before scanning.

Single

One element

That element is automatically the maximum.

Negatives

All negative

Maximum is the least negative value, such as -1.

Dupes

Repeated maximum

Value is unchanged; index depends on > vs >=.

Mixed

Positives and negatives

Same scan, no special case needed.

Long

Large values

Use long[] if values may exceed int range.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Lower bound. Unsorted max needs at least n-1 comparisons in the worst case.
  • Idempotent on dups. Multiple copies of the max do not change the returned value.
  • Symmetric twin. Minimum uses the same pass with < instead of >.
  • Online-friendly. You can update the max as new values arrive without storing all of them.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run the sample

  • Trace {14, 7, 25, 31, 10, 42}
  • Expect final max 42

2. All negatives

  • Reproduce Example 2
  • Confirm answer -1

3. Empty guard

  • Call findMax(new int[0])
  • Assert your chosen error policy

4. Max with index

  • Implement Example 3
  • Decide first vs last on ties

Notes

  • Algorithm: running maximum in one pass.
  • Cost: O(n) time, O(1) extra space.
  • Important edge: define behavior for empty arrays.
  • Java has library helpers too, but interviewers often ask for the manual scan first. Large data can combine partial maxima in parallel.

Quick Takeaway: guard empty, seed with arr[0], update on >, return in O(n) time.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single scanO(n)O(1)
Library helperO(n)O(1)
Sort then take lastO(n log n)depends on sort

For unsorted input, a single scan is the standard interview answer.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Guard empty arrays first
  • Seed with arr[0]
  • Use one O(n) scan
  • Mention negatives and duplicates
  • State O(n) time / O(1) space

❌ Don’t

  • Index empty arrays
  • Initialize max to 0 blindly
  • Sort just to find the max
  • Skip the empty-array discussion
  • Forget that -1 > -9

Key Takeaways

Knowledge Unlocked

Five things to remember about array maximum

Find the largest value the interview-friendly way.

5
Core concepts
0 02

Seed

Start at arr[0]

Init
! 03

Empty

Guard first

Safety
04

Negatives

Still works

Edge
O 05

Cost

O(n) / O(1)

Analysis

❓ Frequently Asked Questions

It picks the first element as the initial candidate, then every later element gets compared against it.
There is no maximum value for an empty array. Handle this case explicitly with an error or validation.
Yes. The maximum is still the greatest value, even if it is negative.
The algorithm still returns that maximum value. Duplicates do not change the answer.
No. Sorting is usually slower than a single scan when you only need the maximum.
One pass over n elements: O(n) time and O(1) extra space.
Libraries can help in production, but interviews often ask you to write the manual linear scan first so you show the comparison logic.
Same one-pass pattern; only the comparison flips from greater-than to less-than.

Did you Know? 🔊

Finding 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.

Continue to Array Minimum

Learn the same one-pass pattern with the opposite comparison to find the smallest value.

Array minimum tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful