DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 64

The task is to find the largest difference between any two numbers in a given array.

The boilerplate code

function largestDiff(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If there are no elements or just one element in the array, the difference is 0.

if(!arr || arr.length < 2) return 0;
Enter fullscreen mode Exit fullscreen mode

Find the smallest number and the largest number in the array.

let min = Infinity;
  let max = -Infinity;

  for (let num of arr) {
    if (num < min) min = num;
    if (num > max) max = num;
  }
Enter fullscreen mode Exit fullscreen mode

The difference is the largest number between any 2 numbers in the array

return max - min
Enter fullscreen mode Exit fullscreen mode

The final code

function largestDiff(arr) {
  // your code here
  if(!arr || arr.length < 2) return 0;

  let min = Infinity;
  let max = -Infinity;

  for(let num of arr) {
    if(num < min) min = num;
    if(num > max) max = num;
  }
  return max - min;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)