Exercise 17: Find Maximum Difference in Array

Problem Statement

Create a function `maxDifference(arr)` that returns maximum difference (max - min) in array. Example: maxDifference([3, 7, 2, 9, 1]) → 8 (9 - 1)

Sample Output:

maxDifference([3, 7, 2, 9, 1]) => 8
maxDifference([10, 5, 20]) => 15

Solution

const maxDifference = (arr) => {
  const nums = arr.filter(n => typeof n === "number" && Number.isFinite(n));
  if (nums.length < 2) return null;
  return Math.max(...nums) - Math.min(...nums);
};

Explanation

Overall Goal:

  • Array me maximum aur minimum ka difference find karna.

Line 1: Function header

  • const maxDifference = (arr) => {

Line 2: Filter valid

  • const nums = arr.filter(n => typeof n === "number" && Number.isFinite(n));

Line 3: Validation

  • if (nums.length < 2) return null;

Line 4: Calculate

  • return Math.max(...nums) - Math.min(...nums);

Real world:

  • Data analysis: range calculation.
  • Statistics: spread calculation.