Find the largest difference【BFE.dev】

本文介绍了如何在JavaScript中使用Math库函数和for循环来找到数组中两数的最大差值,讨论了处理边缘情况的方法,并提供了两种不同的实现方式:一种利用Math.max和Math.min,另一种使用循环找出最大值和最小值。
摘要由CSDN通过智能技术生成

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
}
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值