Minimum sum of absolute differences of pairs in a triplet from three arrays | C ++ program for the above approach ; Function to find the value closest to K in the array A [ ] ; Initialize close value as the end element ; Find lower bound of the array ; If lower_bound is found ; If lower_bound is not the first array element ; If * ( it - 1 ) is closer to k ; Return closest value of k ; Function to find the minimum sum of abs ( arr [ i ] - brr [ j ] ) and abs ( brr [ j ] - crr [ k ] ) ; Sort the vectors arr and crr ; Initialize minimum as INT_MAX ; Traverse the array brr [ ] ; Stores the element closest to val from the array arr [ ] ; Stores the element closest to val from the array crr [ ] ; If sum of differences is minimum ; Update the minimum ; Print the minimum absolute difference possible ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int closestValue ( vector < int > A , int k ) { int close = A . back ( ) ; auto it = lower_bound ( A . begin ( ) , A . end ( ) , k ) ; if ( it != A . end ( ) ) { close = * it ; if ( it != A . begin ( ) ) { if ( ( k - * ( it - 1 ) ) < ( close - k ) ) { close = * ( it - 1 ) ; } } } return close ; } void minPossible ( vector < int > arr , vector < int > brr , vector < int > crr ) { sort ( arr . begin ( ) , arr . end ( ) ) ; sort ( crr . begin ( ) , crr . end ( ) ) ; int minimum = INT_MAX ; for ( int val : brr ) { int arr_close = closestValue ( arr , val ) ; int crr_close = closestValue ( crr , val ) ; if ( abs ( val - arr_close ) + abs ( val - crr_close ) < minimum ) minimum = abs ( val - arr_close ) + abs ( val - crr_close ) ; } cout << minimum ; } int main ( ) { vector < int > a = { 1 , 8 , 5 } ; vector < int > b = { 2 , 9 } ; vector < int > c = { 5 , 4 } ; minPossible ( a , b , c ) ; return 0 ; }