Return the maximum and minimum values of an integer array in a single pass.
Initialize both min and max to the first element, then scan the rest, updating each as needed. One pass is O(n) and beats sorting. Handle empty arrays explicitly.
public static int[] minMax(int[] a) {
int min = a[0], max = a[0];
for (int x : a) { if (x < min) min = x; if (x > max) max = x; }
return new int[]{min, max};
}function minMax(a) {
let min = a[0], max = a[0];
for (const x of a) { if (x < min) min = x; if (x > max) max = x; }
return { min, max };
}def min_max(a):
return min(a), max(a)Finding extremes in one pass is how you report the fastest/slowest measurement from a stream without sorting everything.
A candidate initializes max to 0. Why does that fail for an all-negative array?