# Find three closest elements from given three sorted arrays in C++

C++Server Side ProgrammingProgramming

Suppose we have three sorted arrays A, B and C, and three elements i, j and k from A, B and C respectively such that max(|A[i] – B[i]|, |B[j] – C[k]|, |C[k] – A[i]|) is minimized. So if A = [1, 4, 10], B = [2, 15, 20], and C = [10, 12], then output elements are 10, 15, 10, these three from A, B and C.

Suppose the size of A, B and C are p, q and r respectively. Now follow these steps to solve this −

• i := 0, j := 0 and k := 0
• Now do the following while i < p and j < q and k < r.
• Find min and max of A[i], B[j] and C[k]
• Calculate diff := max(X, Y, Z) - min(A[i], B[j], C[k])
• If the result is less than current result, then change it to new result
• Increment the pointer of the array which contains the minimum.

## Example

#include <iostream>
using namespace std;
void getClosestElements(int A[], int B[], int C[], int p, int q, int r) {
int diff = INT_MAX;
int i_final =0, j_final = 0, k_final = 0;
int i=0,j=0,k=0;
while (i < p && j < q && k < r) {
int min_element = min(A[i], min(B[j], C[k]));
int max_element = max(A[i], max(B[j], C[k]));
if (max_element-min_element < diff){
i_final = i, j_final = j, k_final = k;
diff = max_element - min_element;
}
if (diff == 0)
break;
if (A[i] == min_element)
i++;
else if (B[j] == min_element)
j++;
else
k++;
}
cout << A[i_final] << " " << B[j_final] << " " << C[k_final];
}
int main() {
int A[] = {1, 4, 10};
int B[] = {2, 15, 20};
int C[] = {10, 12};
int p = sizeof A / sizeof A[0];
int q = sizeof B / sizeof B[0];
int r = sizeof C / sizeof C[0];
cout << "Closest elements are: ";
getClosestElements(A, B, C, p, q, r);
}

## Output

Closest elements are: 10 15 10
Published on 19-Dec-2019 07:50:41