# Minimize (max(A[i], B[j], C[k]) – min(A[i], B[j], C[k])) of three different sorted arrays in Python

PythonServer Side ProgrammingProgramming

Suppose we have three sorted arrays A, B, and C (these can be of different sizes), we have to find compute the minimum absolute difference between the maximum and minimum number of any triplet (A[i],B[j],C[k]) such that they are under arrays A, B and C respectively,

So, if the input is like A : [ 2, 5, 6, 9, 11 ], B : [ 7, 10, 16 ], C : [ 3, 4, 7, 7 ] , then the output will be 1 as by selecting A[i] = 6 B[j] = 7 and C[k] = 7, we will get the minimum difference as max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) = |7-6| = 1

To solve this, we will follow these steps −

• i := size of A - 1
• j := size of B - 1
• k := size of C - 1
• minimum_dfference := |maximum of A[i], B[j], C[k] - minimum of A[i], B[j], C[k]|
• while i is not same as -1 and j is not same as -1 and k is not same as -1, do
• current_diff := |maximum of A[i], B[j], C[k] - minimum of A[i], B[j], C[k]|
• if current_diff < minimum_dfference is non-zero, then
• minimum_dfference := current_diff
• maximum_term := maximum of A[i], B[j], C[k]
• if A[i] is same as maximum_term, then
• i := i - 1
• otherwise when B[j] is same as maximum_term, then
• j := j - 1
• otherwise,
• k := k - 1>
• return minimum_dfference

## Example

Let us see the following implementation to get better understanding −

Live Demo

def solve(A, B, C):
i = len(A) - 1
j = len(B) - 1
k = len(C) - 1
minimum_dfference = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k]))
while i != -1 and j != -1 and k != -1:
current_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k]))
if current_diff < minimum_dfference:
minimum_dfference = current_diff
maximum_term = max(A[i], B[j], C[k])
if A[i] == maximum_term:
i -= 1
elif B[j] == maximum_term:
j -= 1
else:
k -= 1
return minimum_dfference
A = [ 2, 5, 6, 9, 11 ]
B = [ 7, 10, 16 ]
C = [ 3, 4, 7, 7 ]
print(solve(A, B, C))

## Input

A = [ 2, 5, 6, 9, 11 ] B = [ 7, 10, 16 ] C = [ 3, 4, 7, 7 ]

## Output

1