Minimum and Maximum

Basic Algorithms
≈ 2 min read

Keep the best result seen so far

You do not need to sort all the data to find a minimum or maximum. It is enough to go through the values once and keep the best value seen so far. For a minimum, a new value replaces the current result when it is smaller; for a maximum, when it is larger.

int min = numbers[0];

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

After the first i elements have been processed, min stores the smallest value among them. Each next element either leaves the result unchanged or becomes the new minimum.

Why start with the first element

For a non-empty array, its first element is the safest initial minimum. It definitely belongs to the data being compared, so there is no need to invent an artificial “very large” number.

For example, initializing with 0 would break minimum search for the array {5, 8, 12}: zero is smaller than every element, even though zero is not in the array.

The array must be non-empty before accessing numbers[0]. If an empty input is allowed by the problem statement, handle it separately.

When you need the position as well as the result

Sometimes a problem asks for the index of the minimum or maximum element. In that case, it is convenient to store the index of the best value rather than the value itself: the value can always be obtained through the index.

int maxIndex = 0;

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

If the same maximum occurs several times, this code keeps the index of the first one, because the update happens only for a strict > comparison. If the problem requires the last maximum, the comparison rule must be different.