JavaScript中两个元素的总和小于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