Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 1.37 KB

File metadata and controls

36 lines (27 loc) · 1.37 KB

Solution

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.
}

Short story

This was pretty straightforward. Though, I see a few people have shared different solutions and it is interesting to understand them.

Algorithm

  1. You sort the array in ascending order
  2. You take difference by subtracting them, though the order doesn't matter
  3. As we will use Math.abs that will remove the significance of the order in which we subtract

Code overview

  1. We cover an edge case where array arr is empty
  2. We sort the array in ascending order (b - a) as a comparator
  3. We take the difference by subtracting the last sortedArr[sortedArr.length -1] and first element of array sortedArr[0]
  4. 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.