Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Problem Statement
Given an array of numbers and a target value, find the maximum sum of any two elements that is still less than the target.
For example:
const arr = [34, 75, 33, 23, 1, 24, 54, 8]; const num = 60;
The output should be 58 because 34 + 24 = 58 is the greatest sum which is less than 60.
Algorithm Approach
We use a two-pointer technique after sorting the array:
- Sort the array in ascending order
- Use two pointers: one at start, one at end
- If sum is less than target, update maximum and move left pointer right
- If sum is greater or equal, move right pointer left
Implementation
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
Output
58
Step-by-Step Execution
const arr2 = [34, 75, 33, 23, 1, 24, 54, 8];
const num2 = 60;
const lessSumDetailed = (arr, num) => {
console.log("Original array:", arr);
arr.sort((a, b) => a - b);
console.log("Sorted array:", arr);
let max = -1;
let i = 0;
let j = arr.length - 1;
while(i
Output
Original array: [ 34, 75, 33, 23, 1, 24, 54, 8 ]
Sorted array: [ 1, 8, 23, 24, 33, 34, 54, 75 ]
Checking: 1 + 75 = 76
Sum 76 is too large, moving right pointer
Checking: 1 + 54 = 55
Sum 55 is valid, updating max to 55
Checking: 8 + 54 = 62
Sum 62 is too large, moving right pointer
Checking: 8 + 34 = 42
Sum 42 is valid, updating max to 55
Checking: 23 + 34 = 57
Sum 57 is valid, updating max to 57
Checking: 24 + 34 = 58
Sum 58 is valid, updating max to 58
Final result: 58
Edge Cases
// Case 1: No valid sum exists
const arr3 = [10, 20, 30];
const num3 = 25;
console.log("No valid sum:", lessSum(arr3, num3)); // -1
// Case 2: All sums are valid
const arr4 = [1, 2, 3, 4];
const num4 = 10;
console.log("All sums valid:", lessSum(arr4, num4)); // 7 (3+4)
Output
No valid sum: -1
All sums valid: 7
Time and Space Complexity
- Time Complexity: O(n log n) due to sorting
- Space Complexity: O(1) for the algorithm (excluding sort space)
Conclusion
The two-pointer technique after sorting provides an efficient solution to find the maximum sum of two elements less than a target. This approach avoids checking all possible pairs, reducing time complexity from O(n²) to O(n log n).
