DEV Community

jser
jser

Posted on • Edited on

BFE.dev #107. Find the largest difference

https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

Alt Text

This article is about the coding problem BFE.dev#107. Find the largest difference

just coding

Obviously we could the max difference by subtracting the largest number with smallest one, so below is the straight approach.

function largestDiff(arr) {
  if (arr.length === 0) return 0
  return Math.abs(Math.max(...arr) - Math.min(...arr))
}
Enter fullscreen mode Exit fullscreen mode

Or we could get min/max at the same time.

Above approach gets max first and then min, while we could get them at the same loop, by just keeping track of the min/max.

function largestDiff(arr) {
  if (arr.length === 0) return 0

  let min = Infinity
  let max = -Infinity
  let result = Infinity

  for (let item of arr) {
    if (item < min) {
      min = item
      result = max - min
    }

    if (item > max) {
      max = item
      result = max - min
    }
  }

  return result
}
Enter fullscreen mode Exit fullscreen mode

The time complexity doesn't change though, they are still O(n) as the same one.

Passed

This is a fairly simple problem.

Alt Text

Interested to try by yourself? Have a try at BFE.dev https://bigfrontend.dev/problem/Find-the-largest-difference

Top comments (0)