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
}
If there are no elements or just one element in the array, the difference is 0.
if(!arr || arr.length < 2) return 0;
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;
}
The difference is the largest number between any 2 numbers in the array
return max - min
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;
}
That's all folks!
Top comments (0)