Given three sorted (non-empty) arrays A, B, and C. It is necessary to find a triplet of numbers A[i], B[j], C[k] for which the expression (max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) would be the minimum of all possible triples.
If there are several triplets with the same value, print the one closest to the beginning of the arrays (priority A, B, C).
I'm trying to implement this algorithm problem, but I'm getting runtime error at the second testcase.
A = []
x = int(input())
for i in range(0, x):
ele = int(input())
A.append(ele)
fnum = A[0]
B = []
y = int(input())
for i in range(0, y):
ele2 = int(input())
B.append(ele2)
C = []
z = int(input())
for i in range(0, z):
ele3 = int(input())
C.append(ele3)
def solve(A, B, C):
i = len(A) - 1
j = len(B) - 1
k = len(C) - 1
min_diff = 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 < min_diff:
min_diff = current_diff
max_term = max(A[i], B[j], C[k])
if A[i] == max_term:
i -= 1
elif B[j] == max_term:
j -= 1
else:
k -= 1
return min_diff
print("Numbers =", fnum, ele2, ele3)
print("Result =", solve(A, B, C))

itertools.product()directly into amin()with custom key function:(i, el1), (j, el2), (k, el3) = min(product(enumerate(A), enumerate(B), enumerate(C)), key=lambda x: max(x[0][1], x[1][1], x[2][1]) - min(x[0][1], x[1][1], x[2][1])). If you don't need indexes it will look more elegant:el1, el2, el3 = min(product(A, B, C), key=lambda x: max(x) - min(x))min(max(x) - min(x) for x in product(A, B, C))