SwadhyAI Notes

All Java notes

How to Find Min and Max in Array in Java

The Challenge

Find both minimum and maximum elements in a single pass!

Solution

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

for (int num : numbers) {
    if (num < min) {
        min = num;
    }
    if (num > max) {
        max = num;
    }
}

System.out.println("Min: " + min + ", Max: " + max);
// Output: Min: 1, Max: 9

Did You Know?

Finding both min and max together is more efficient than two separate loops - you only traverse the array once!

Pro Tip

Use Java 8 streams for a functional approach:

java
import java.util.IntSummaryStatistics;
import java.util.Arrays;

IntSummaryStatistics stats = Arrays.stream(numbers).summaryStatistics();
System.out.println("Min: " + stats.getMin() + ", Max: " + stats.getMax());

Real-World Use Cases

  • Data analysis: Find range of values
  • Graphics: Calculate bounding box
  • Statistics: Determine data spread
›Short versionOpen if you only have a minute.
  • Initialize both from the first element and update them in one pass.
  • Two separate scans work and touch every element twice.
  • Sorting finds both ends and reorders the array.
  • A single element is both the minimum and the maximum.

Minimum and maximum together

Find the smallest and largest values in one pass.

Working approach

  • Reject an empty array.
  • Set min and max to values[0].
  • For each later value, update whichever side it beats.

Walk the sample

  1. Values 4, 1, 9
  2. min and max start at 4
  3. 1 updates min
  4. 9 updates max
  5. The pair is 1 and 9

The trap

Initializing either side to 0 fails on the same inputs as a lone min or max search, and a sort pays O(n log n) for two numbers.

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

How does one pass compare with sorting when you only need the two ends?

One pass does a small constant amount of work per element and does not write the array.

Arrays.sort is O(n log n) and mutates. The ends are then values[0] and values[length - 1] of a different order than the caller passed in.

Time O(n), space O(1) besides the returned pair.

Easy to get wrong

  • Starting min or max at 0.
  • Sorting to read the first and last indexes.