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
Selected Reading
Find three closest elements from given three sorted arrays in C++
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
- 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
#includeusing 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 Output
Closest elements are: 10 15 10
Advertisements
