Menu Close

Smallest Difference Triplet…FTC

Three arrays of same size are given. Find a triplet such that maximum – minimum in that triplet is minimum of all the triplets. A triplet should be selected in a way such that it should have one number from each of the three given arrays.

If there are 2 or more smallest difference triplets, then the one with the smallest sum of its elements should be displayed.

Input: arr1 = [5, 2, 8]
       arr2 = [10, 7, 12]
       arr3 = [9, 14, 6]

Output: [8, 7, 6]
def tript(arr1, arr2, arr3, n):
    arr1.sort()
    arr2.sort()
    arr3.sort()

    t1,t2,t3 = 0,0,0
    i,j,k = 0,0,0
    diff = 1000000

    while(i<n and j<n and k<n):
        sum = arr1[i]+arr2[j]+arr3[k]
        maxi = max( max(arr1[i],arr2[j]), arr3[k])
        mini = min( min(arr1[i],arr2[j]), arr3[k])
        if(mini == arr1[i]): i += 1
        elif(mini == arr2[j]): j += 1
        else: k += 1

        if (diff > (maxi-mini)):
            diff = maxi - mini
            t3 = maxi
            t2 = sum-(maxi+mini)
            t1 = mini
    return [t1,t2,t3]

Arr1=list(map(int,input('Arr1: ').split(' ')))
Arr2=list(map(int,input('Arr2: ').split(' ')))
Arr3=list(map(int,input('Arr3: ').split(' ')))

L=tript(Arr1,Arr2,Arr3,len(Arr1))
print(sorted(L,reverse=True))

INPUT_1:
Arr1:  5  2  8
Arr2:  10  7  12
Arr3:  9  14  6

OUTPUT:
[ 7,  6, 5 ]


INPUT_2:
Arr1:  15  12  18  19
Arr2:  10  17  13  8
Arr3:  14  16  11  5

OUTPUT:
[ 12,  11,  10 ]


 


INPUT_3:
Arr1:  2  3  5
Arr2:  15  48 20
Arr3:  10  11  2

OUTPUT:
[ 15,  10,  5 ]


INPUT_4:
Arr1:  6  2  1
Arr2:  5  9  7
Arr3:  12  6  5

OUTPUT:
[ 6,  5,  5 ]


ILLUSTRATION

Executed using python3