19. Find the Difference Between Maximum and Minimum
Given an array of numbers, find the difference between the largest and smallest values.
How It Works & Algorithmic Design
Instead of sorting the array:
- Track the maximum value.
- Track the minimum value.
- Traverse the array once and update both when necessary.
- Return
max - min. - Handle an empty array appropriately.
Why This Approach Works Best
Sorting is unnecessary. Both extremes can be found in one pass, resulting in $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
Input:
[4, 10, 2, 8, 15]Maximum is 15 and minimum is 2.
Calculation:
15 - 2 = 13Subtract the smallest value from the largest value.
Output:
13The range between the minimum and maximum is 13.
Answer: Find max-min difference
function maxMinDifference(arr) {
if (!arr.length) return null;
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return max - min;
}💡 Track both extremes during one traversal and subtract them at the end.
Key Takeaways
- Maximum and minimum can be found simultaneously.
- Sorting is unnecessary for calculating the range.
- The algorithm requires O(n) time and O(1) auxiliary space.