19. Find the Difference Between Maximum and Minimum

Difficulty:EasyPattern:Linear ScanTime:O(n)Space:O(1)

Given an array of numbers, find the difference between the largest and smallest values.

How It Works & Algorithmic Design

Instead of sorting the array:

  1. Track the maximum value.
  2. Track the minimum value.
  3. Traverse the array once and update both when necessary.
  4. Return max - min.
  5. 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 = 13
Subtract the smallest value from the largest value.
Output: 13
The 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.