Sum of two elements just less than n in JavaScript


We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a single number, num, as the second argument.

The function should then find two such numbers whose sum is greatest in the array but just less than the number num. If there exists no two such numbers whose sum is less than num, our function should return -1.

For example −

If the input array and the number are −

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

Then the output should be −

const output = 58;

because 34 + 24 is the greatest sum which is less than 60

Example

The code for this will be −

 Live Demo

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));

Output

And the output in the console will be −

58

Updated on: 27-Feb-2021

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements