Submission link - https://bigfrontend.dev/problem/Find-the-largest-difference/discuss/651
/**
* @param {number[]} arr
* @return {number}
*/
function largestDiff(arr) {
if(!arr.length) return 0; // if empty array then return 0
const sortedArr = arr.sort((a, b) => b - a); // sort array in ascending order
return Math.abs(sortedArr[sortedArr.length -1] - sortedArr[0]); // substract last and first value to get largest diff.
}
This was pretty straightforward. Though, I see a few people have shared different solutions and it is interesting to understand them.
- You sort the array in ascending order
- You take difference by subtracting them, though the order doesn't matter
- As we will use
Math.abs
that will remove the significance of the order in which we subtract
- We cover an edge case where array
arr
is empty - We sort the array in ascending order
(b - a)
as a comparator - We take the difference by subtracting the last
sortedArr[sortedArr.length -1]
and first element of arraysortedArr[0]
- We apply
Math.abs
on them to get the largest difference
I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.