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
Selected Reading
Find the closest pair from two sorted arrays in c++
Suppose we have two sorted arrays and a number x, we have to find the pair whose sum is closest to x. And the pair has an element from each array. We have two arrays A1 [0..m-1] and A2 [0..n-1], and another value x. We have to find the pair A1[i] + A2[j] such that absolute value of (A1[i] + A2[j] – x) is minimum. So if A1 = [1, 4, 5, 7], and A2 = [10, 20, 30, 40], and x = 32, then output will be 1 and 30.
We will start from left of A1 and right from A2, then follow these steps to find such pair
- Initialize diff, this will hold the difference between pair and x
- Initialize two pointer left := 0 and right := n – 1
- While left = 0, do
- if |A1[left] + A2[right] – sum|
- update diff and result
- if (A1[left] + A2[right])
- increase left by 1
- Decrease right by 1
Example
#include#include using namespace std; void findClosestPair(int A1[], int A2[], int m, int n, int x) { int diff = INT_MAX; int left_res, right_res; int left = 0, right = n-1; while (left =0) { if (abs(A1[left] + A2[right] - x) x) right--; else left++; } cout Output
The closest pair is [1, 30]
Advertisements
