Bootstrap

Find the largest difference【BFE.dev】

No.107 question in BFE.dev, link here Find the largest difference.

largestDiff([-1, 2,3,10, 9])
// 11,  obviously Math.abs(-1 - 10) is the largest

largestDiff([])
// 0

largestDiff([1])
// 0

In this question, we are asked to get the largest difference among a pair of numbers. For example, in the first case which the question provided, the largest diffenence among these numbers are minus 1 and 10, so the absolute value of them is 11.

So to implement the function, we can use Math’s apis, of course we need to check edge case first, when arr.length equals to 0 or 1 return 0, just like the examples this question provided. Then, just return Math.abs(Math.max(…arr) - Math.min(…arr)), so Math.max to find the maximum value in arr, and Math.min finding the minimum one in arr.

function largestDiff(arr) {
  if (arr.length === 0 || arr.length === 1) return 0
  return Math.abs(Math.max(...arr) - Math.min(...arr))
}

But we can also use another way to solve it, without using Math’s apis, we can use for loop to find maximum value and minimum value in arr, and return max value minus minimum value

function largestDiff(arr) {
  if (arr.length === 0 || arr.length === 1) return 0
  let min = Infinity
  let max = -Infinity
  for (let item of arr) {
    if (item < min) {
      min = item
    } else if (item > max) {
      max = item
    }
  }
  return max - min
}
;