Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,089 questions

40,774 answers

573 users

How to find the pair in array whose sum is nearest to a number N in a sorted array in JavaScript

1 Answer

0 votes
const arr = [3, 5, 7, 12, 18, 20, 23, 27, 30];
 
const size = arr.length;

const N = 22;
   
let left = 0, right = size - 1, sum = 0;
let nearest = Number.MAX_VALUE, nearest_sum = 0; 
let paira = 0, pairb = 0;
  
while (left < right) {
       sum = arr[left] + arr[right];
       if (Math.abs(N - sum) < nearest) {
           nearest = Math.abs(N -sum);
           nearest_sum = sum;
           paira = arr[left];
           pairb = arr[right];
       }
           
       if (sum > N)
           right--;
       else if (sum <= N)
                left++;
        }
          
console.log(nearest_sum);
console.log(paira + " " + pairb);
 
 
 
 
/*
run:
   
23
"3 20"
   
*/

 





answered Dec 9, 2021 by avibootz
...