JavaScript 中小于 n 的两个元素的和\n


我们要求编写一个 JavaScript 函数,该函数接受一个数字数组 arr 作为第一个参数和一个数字 num 作为第二个参数。

然后,该函数应该找到数组中两个数字的和最大且恰好小于数字 num。如果不存在和小于 num 的两个这样的数字,则我们的函数应返回 -1。

例如 −

如果输入数组和数字为 −

const arr = [34, 75, 33, 23, 1, 24, 54, 8];
const num = 60;

则输出应为 −

const output = 58;

因为 34 + 24 是小于 60 的最大和

示例

该代码如下 −

 实时演示

const arr = [34, 75, 33, 23, 1, 24, 54, 8];
const num = 60;
const lessSum = (arr = [], num = 1) => {
   arr.sort((a, b) => a - b);
   let max = -1;
   let i = 0;
   let j = arr.length - 1;
   while(i < j){
      let sum = arr[i] + arr[j];
      if(sum < num){
         max = Math.max(max,sum);
         i++;
      }else{
         j--;
      };
   };
   return max;
};
console.log(lessSum(arr, num));

输出

控制台中的输出将为 −

58

更新于:27-Feb-2021

123 浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告