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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <climits>

int main()
{
  int arr[]= {3, 5, 7, 12, 18, 20, 23, 27, 30};
  int size = sizeof(arr)/sizeof(arr[0]);
   
  int N = 22;
 
  int left = 0, right = size - 1, sum = 0;
  int nearest = INT_MAX, nearest_sum; 
  int paira, pairb;
   
  while(left < right) {
    sum = arr[left] + arr[right];
     
    if (abs(N - sum) < nearest) {
      nearest = abs(N -sum);
      nearest_sum = sum;
      paira = arr[left];
      pairb = arr[right];
    }
     
    if (sum > N)
      right--;
    else if (sum <= N)
      left++;
  }
  std::cout << nearest_sum << "\n";
  std::cout << paira << " " << pairb;
}
 
 
 
 
/*
run:
 
23
3 20
 
*/

 



answered Dec 9, 2021 by avibootz
edited Dec 9, 2021 by avibootz
...