SwadhyAI Notes

All Java notes

How to Find Largest Element in Array in Java

The Challenge

Find the maximum (largest) element in an array!

Solutions

Method 1: Using Loop

java
int[] numbers = {5, 2, 8, 1, 9};
int max = numbers[0];

for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

System.out.println("Largest: " + max);
// Output: Largest: 9

Method 2: Using Arrays.sort()

java
import java.util.Arrays;

int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
int max = numbers[numbers.length - 1];

System.out.println("Largest: " + max);
// Output: Largest: 9

Method 3: Using Java 8 Streams

java
import java.util.Arrays;

int[] numbers = {5, 2, 8, 1, 9};
int max = Arrays.stream(numbers).max().getAsInt();

System.out.println("Largest: " + max);
// Output: Largest: 9

Did You Know?

You can find both min and max in a single loop by tracking both values simultaneously!

Pro Tip

Find both min and max efficiently:

java
int min = numbers[0], max = numbers[0];
for (int num : numbers) {
    if (num < min) min = num;
    if (num > max) max = num;
}

Real-World Use Cases

  • E-commerce: Find highest price
  • Weather: Find maximum temperature
  • Gaming: Find high score
  • Analytics: Find peak value in dataset
›Short versionOpen if you only have a minute.
  • One pass, starting from the first element.
  • int max = 0 fails when every element is negative: the largest of {-5, -1, -8} is -1, and 0 is not in the array.
  • Sorting to read the last index is O(n log n) and mutates the array.
  • An empty array has no maximum.

Largest element

Find the highest value by scanning the array once.

Working approach

  • Reject an empty array.
  • Set max to values[0].
  • Replace it when a later element is greater.

Walk the sample

  1. Values 4, 9, 2
  2. max starts at 4
  3. 9 replaces it
  4. 2 does not
  5. The result is 9

The trap

A zero initializer looks harmless on the sample {4, 9, 2} and returns 0 for an array of negative scores.

java
static int largest(int[] values) {
    if (values.length == 0) {
        throw new IllegalArgumentException("empty array");
    }
    int max = values[0];
    for (int i = 1; i < values.length; i++) {
        if (values[i] > max) {
            max = values[i];
        }
    }
    return max;
}

What does a max that starts at 0 return for {-5, -1, -8}?

0, if you only update when a value is greater than the current max. None of those numbers is greater than 0.

The largest element is -1. Start from values[0]. A sort would also find it, and would reorder the array to do it.

Time O(n), space O(1).

Easy to get wrong

  • Initializing max to 0.
  • Sorting when a linear scan is enough.