Find Maximum

Java coding interview problem for Array Coding: Find Maximum.

Finding the maximum element in an array is one of the most fundamental array interview questions.

Although it appears simple, this problem teaches one of the most important programming concepts:

  • Array Traversal
  • Comparison Operators
  • Looping
  • Variables
  • Time Complexity
  • Space Complexity

This problem is also the foundation for many advanced interview questions like:

  • Second Largest Element
  • Maximum Difference
  • Maximum Product
  • Stock Buy and Sell
  • Kadane's Algorithm
  • Maximum Subarray Sum

Understanding this problem thoroughly makes many array interview questions much easier.


What is the Maximum Element?

The maximum element is the largest value present in an array.

Example

Array

[12, 45, 8, 23, 90, 17]

Maximum

90

Another Example

[-10, -3, -50, -1]

Maximum

-1

Why is this Question Asked in Interviews?

Interviewers ask this question because it tests your understanding of:

  • Arrays
  • Loops
  • Comparisons
  • Variables
  • Time Complexity
  • Edge Cases

It is often the first step before solving more difficult array problems.


Real-World Applications

Finding the maximum value is used everywhere.


Student Result Analysis

Marks

78

82

91

88

67

Highest Marks

91

Sales Analytics

Monthly Sales

$15,000

$22,000

$18,000

$27,000

Highest Sales

$27,000

Temperature Monitoring

Daily Temperatures

28

30

34

26

32

Highest Temperature

34°C

Stock Market

Share Prices

120

140

155

132

Highest Price

155

Gaming

Player Scores

2400

1800

3500

2900

Highest Score

3500

Problem Statement

Given an integer array,

find the largest element.


Example 1

Input

[10, 20, 30, 40]

Output

40

Example 2

Input

[99]

Output

99

Example 3

Input

[-5, -10, -2]

Output

-2

Example 4

Input

[7, 7, 7, 7]

Output

7

Understanding Maximum Search

Suppose we have

[15, 8, 42, 19, 65]

Start

Maximum = 15

Compare

8

↓

Smaller

Ignore

Compare

42

↓

Greater

Maximum = 42

Compare

19

↓

Smaller

Ignore

Compare

65

↓

Greater

Maximum = 65

Final Answer

65

Mathematical Concept

Suppose

Maximum = First Element

For every element

If

Current > Maximum

↓

Update Maximum

Repeat until the array ends.


Array Traversal Visualization

Input

[5, 18, 12, 25, 9]
Maximum

↓

5

↓

Compare

18

↓

Update

Maximum = 18

↓

Compare

12

↓

Ignore

↓

Compare

25

↓

Update

Maximum = 25

↓

Compare

9

↓

Ignore

Result

25

Dry Run

Input

[12, 45, 8, 23, 90]
Current Element Maximum Action
12 12 Initialize
45 45 Update
8 45 Ignore
23 45 Ignore
90 90 Update

Output

90

Approach 1 — Linear Search (Recommended)

This is the best interview solution.

The idea is simple:

  • Assume the first element is the maximum.
  • Compare every remaining element.
  • Update the maximum whenever a larger value is found.

Algorithm

  1. Initialize maximum as the first element.
  2. Traverse the array.
  3. Compare current element with maximum.
  4. If larger, update maximum.
  5. Return maximum.

Java Program

public class FindMaximumLinear {

    public static int findMaximum(int[] numbers) {

        int maximum = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] > maximum) {

                maximum = numbers[i];

            }

        }

        return maximum;

    }

    public static void main(String[] args) {

        int[] numbers = {12, 45, 8, 23, 90};

        System.out.println("Maximum = " + findMaximum(numbers));

    }

}

Output

Maximum = 90

Step-by-Step Code Explanation

Initialize

int maximum = numbers[0];

Traverse

for(...)

Compare

numbers[i] > maximum

Update

maximum = numbers[i];

Return

maximum

Dry Run of Linear Search

Input

[4, 9, 2, 15, 6]
Current Maximum Action
4 4 Initialize
9 9 Update
2 9 Ignore
15 15 Update
6 15 Ignore

Output

15

Advantages

  • Best interview solution.
  • Easy to understand.
  • Single traversal.
  • Constant extra space.
  • Works for negative numbers.

Drawbacks

  • Traverses the complete array.
  • Cannot terminate early because a larger value may appear later.

Approach 2 — Using Java Collections.max()

Java Collections Framework provides a built-in method to find the maximum element.

This approach is concise but requires converting the array into a collection.


Algorithm

  1. Convert the array to a List.
  2. Call Collections.max().
  3. Return the maximum element.

Java Program

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindMaximumCollections {

    public static void main(String[] args) {

        Integer[] numbers = {12, 45, 8, 23, 90};

        List<Integer> list = Arrays.asList(numbers);

        int maximum = Collections.max(list);

        System.out.println("Maximum = " + maximum);

    }

}

Output

Maximum = 90

Step-by-Step Code Explanation

Create an Integer array.

Integer[] numbers = {12, 45, 8, 23, 90};

Convert to a List.

List<Integer> list = Arrays.asList(numbers);

Find maximum.

Collections.max(list);

Print the result.

System.out.println(maximum);

Time & Space Complexity

Approach Time Extra Space
Linear Search O(n) O(1)
Collections.max() O(n) O(1)*

*The Arrays.asList() method creates a fixed-size list backed by the original array without copying the elements. If the input is already an Integer[], the additional space is effectively constant.


Comparison of Approaches

Feature Linear Search Collections.max()
Interview Friendly ⭐⭐⭐⭐⭐ ⭐⭐⭐
Performance ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Easy to Understand ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐
Extra Library Required ❌ ✅
Works with Primitive int[] ✅ ❌

Advantages

  • Both approaches run in O(n) time.
  • Linear Search requires no library methods.
  • Collections.max() produces concise and readable code.
  • Both correctly handle duplicate and negative values.

Drawbacks

  • Linear Search requires manual implementation.
  • Collections.max() works with collections, not primitive int[] arrays directly.
  • Converting primitive arrays to collections requires boxing, which adds overhead.

Approach 3 — Using Java Streams

Java 8 introduced the Stream API, making many collection and array operations concise and expressive.

For finding the maximum element, we can use:

Arrays.stream(array).max()

This approach internally traverses the array only once.


Algorithm

  1. Convert the array into a stream.
  2. Call the max() terminal operation.
  3. Retrieve the result using getAsInt().
  4. Return the maximum element.

Java Program

import java.util.Arrays;

public class FindMaximumStreams {

    public static int findMaximum(int[] numbers) {

        return Arrays.stream(numbers)
                     .max()
                     .getAsInt();

    }

    public static void main(String[] args) {

        int[] numbers = {12, 45, 8, 23, 90};

        System.out.println("Maximum = " + findMaximum(numbers));

    }

}

Output

Maximum = 90

Step-by-Step Explanation

Convert the array into a stream.

Arrays.stream(numbers)

Find the maximum value.

.max()

Retrieve the integer.

.getAsInt()

Return the result.


Advantages

  • Modern Java style.
  • Very concise.
  • Single traversal.
  • Excellent readability.

Drawbacks

  • Slight Stream overhead.
  • getAsInt() throws an exception for an empty array unless checked.
  • Less commonly expected than manual traversal in beginner interviews.

Approach 4 — Divide and Conquer

Instead of scanning the array sequentially, we divide it into two halves.

Find the maximum in the left half.

Find the maximum in the right half.

Return the larger of the two.

This technique is useful for understanding recursion and forms the basis of many advanced algorithms.


Visualization

Input

[12, 45, 8, 23, 90, 17]

Split

           [12 45 8 23 90 17]

             /            \

      [12 45 8]        [23 90 17]

        /     \          /      \

      Max=45          Max=90

             \        /

            Maximum = 90

Algorithm

  1. Divide the array into two halves.
  2. Recursively find the maximum in both halves.
  3. Compare both maximum values.
  4. Return the larger value.

Java Program

public class FindMaximumDivideConquer {

    public static int findMaximum(int[] numbers, int left, int right) {

        if (left == right) {

            return numbers[left];

        }

        int mid = (left + right) / 2;

        int leftMaximum = findMaximum(numbers, left, mid);

        int rightMaximum = findMaximum(numbers, mid + 1, right);

        return Math.max(leftMaximum, rightMaximum);

    }

    public static void main(String[] args) {

        int[] numbers = {12, 45, 8, 23, 90, 17};

        System.out.println(findMaximum(numbers, 0, numbers.length - 1));

    }

}

Output

90

Advantages

  • Demonstrates recursion.
  • Foundation for divide-and-conquer algorithms.
  • Useful for parallel processing.

Drawbacks

  • More complex.
  • Recursive call overhead.
  • Not preferred for this simple problem.

Approach 5 — Using Sorting

Another approach is to sort the array.

After sorting,

the last element becomes the maximum.

Although simple,

this is not recommended because sorting is more expensive than simply scanning the array.


Visualization

Input

[12, 45, 8, 23, 90]

Sort

[8, 12, 23, 45, 90]

Last Element

90

Algorithm

  1. Sort the array.
  2. Return the last element.

Java Program

import java.util.Arrays;

public class FindMaximumSorting {

    public static int findMaximum(int[] numbers) {

        Arrays.sort(numbers);

        return numbers[numbers.length - 1];

    }

    public static void main(String[] args) {

        int[] numbers = {12, 45, 8, 23, 90};

        System.out.println(findMaximum(numbers));

    }

}

Output

90

Advantages

  • Very easy to understand.
  • Useful when sorting is already required.

Drawbacks

  • Time complexity becomes O(n log n).
  • Modifies the original array.
  • Much slower than Linear Search.

Handling Negative Numbers

A common interview mistake is initializing the maximum to 0.

Example

[-10, -5, -3]

Wrong Initialization

int maximum = 0;

Result

0

Correct Answer

-3

Always initialize with the first element.

int maximum = numbers[0];

Integer Overflow Considerations

Finding the maximum only compares values.

It does not perform arithmetic operations, so integer overflow is generally not a concern.

Example

Integer.MAX_VALUE

can safely be compared.

if (numbers[i] > maximum)

However, if later calculations are performed on the maximum value (such as addition or multiplication), overflow must then be considered.


Edge Cases

Input Output
[5] 5
[-5] -5
[-10,-5,-2] -2
[7,7,7] 7
[Integer.MIN_VALUE] Integer.MIN_VALUE
[Integer.MAX_VALUE] Integer.MAX_VALUE

Time & Space Complexity

Approach Time Extra Space
Linear Search O(n) O(1)
Collections.max() O(n) O(1)*
Java Streams O(n) O(1)
Divide & Conquer O(n) O(log n)
Sorting O(n log n) O(log n)**

*For an existing Integer[] wrapped by Arrays.asList(). Boxing a primitive int[] would require additional space.

**Arrays.sort(int[]) uses Dual-Pivot Quicksort, which typically requires O(log n) stack space.


Comparison of All Approaches

Approach Interview Friendly Performance Extra Space Best Use Case
Linear Search ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ O(1) Recommended solution
Collections.max() ⭐⭐⭐ ⭐⭐⭐⭐⭐ O(1)* Collections
Java Streams ⭐⭐⭐⭐ ⭐⭐⭐⭐ O(1) Modern Java
Divide & Conquer ⭐⭐⭐⭐ ⭐⭐⭐ O(log n) Recursion practice
Sorting ⭐⭐⭐ ⭐⭐ O(log n) Array already being sorted

Common Interview Mistakes

Mistake 1

Initializing maximum as zero.

Wrong

int maximum = 0;

Correct

int maximum = numbers[0];

Mistake 2

Ignoring empty arrays.

Always validate input.

if (numbers == null || numbers.length == 0) {
    throw new IllegalArgumentException("Array must not be empty");
}

Mistake 3

Sorting just to find the maximum.

Sorting is unnecessary.

Linear Search is faster.


Mistake 4

Using Collections.max() directly on int[].

Primitive arrays are not collections.


Mistake 5

Modifying the original array accidentally.

Arrays.sort() changes the array in place.


Interview Follow-up Questions

Q1. Can you find the second largest element?

Q2. Can you find both minimum and maximum in one traversal?

Q3. Can you solve it recursively?

Q4. How would you handle an empty array?

Q5. Which approach is the fastest?

Q7. Can this problem be solved using Streams?

Q8. What if the array contains duplicate maximum values?

Q9. What changes for floating-point arrays?

Q10. How would you process an array too large to fit into memory?


Related Problems

  • Find Minimum Element
  • Second Largest Element
  • Largest and Smallest in One Traversal
  • Maximum Difference
  • Maximum Product Pair
  • Maximum Subarray Sum (Kadane's Algorithm)
  • Peak Element
  • Kth Largest Element

Key Takeaways

  • Finding the maximum element is a foundational array problem.
  • Linear Search is the best interview solution because it is simple, efficient, and uses constant extra space.
  • Java Streams provide a modern and concise alternative.
  • Divide and Conquer introduces recursion and parallelizable thinking.
  • Sorting works but is inefficient for this specific problem.
  • Always initialize the maximum with the first element, not zero.

Frequently Asked Interview Questions

Q1. Which solution is best for interviews?

Linear Search is the preferred answer because it achieves O(n) time with O(1) extra space and is easy to explain.


Q2. Why not sort the array?

Sorting takes O(n log n) time, while Linear Search only needs O(n).


Q3. Why initialize with the first element?

This correctly handles arrays containing only negative numbers.


Yes.

Arrays.stream(array).max() internally traverses the array once and provides a clean Java 8+ solution.


Q5. How do you handle an empty array?

Validate the input before processing.

if (numbers == null || numbers.length == 0) {
    throw new IllegalArgumentException("Array must not be empty");
}

Interview Tip

If an interviewer asks:

"Find the maximum element in an array."

Start with the Linear Search solution because it is the optimal approach.

Then discuss alternative implementations:

  1. Linear Search (Recommended)
  2. Java Streams (Arrays.stream().max())
  3. Collections.max() for collections
  4. Divide and Conquer (Recursive approach)
  5. Sorting (Explain why it is less efficient)

Finally, mention important edge cases:

  • Empty arrays
  • Arrays with negative numbers
  • Duplicate maximum values
  • Single-element arrays

Explaining both the optimal algorithm and its trade-offs demonstrates strong problem-solving skills and interview readiness.