- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 −

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

- Related Questions & Answers
- Product of subarray just less than target in JavaScript
- Two Sum Less Than K in Python
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Generate a list of Primes less than n in Python
- Program to find sum of two numbers which are less than the target in Python
- Maximum sum of n consecutive elements of array in JavaScript
- Count pairs with sum as a prime number and less than n in C++
- Nearest prime less than given number n C++
- Count ordered pairs with product less than N in C++
- What is Less than Operator (<) in JavaScript?
- Python – Elements with factors count less than K
- Mask array elements less than a given value in Numpy
- Find the Number of subarrays having sum less than K using C++
- Alternating sum of elements of a two-dimensional array using JavaScript
- Count the number of words having sum of ASCII values less than and greater than k in C++

Advertisements