Minimize the absolute difference

Given three sorted arrays A, B and Cof not necessarily same sizes.

Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that a, b, c belongs arrays A, B, C respectively. i.e. minimize | max(a,b,c) - min(a,b,c) |.

Example :

Input:

A : [ 1, 4, 5, 8, 10 ]
B : [ 6, 9, 15 ]
C : [ 2, 3, 6, 6 ]

Output:

1

Explanation: We get the minimum difference for a=5, b=6, c=6 as | max(a,b,c) - min(a,b,c) | = |6-5| = 1.

public class Solution {
    public int solve(int[] A, int[] B, int[] C) {
        int i, j, k;
        i = A.length - 1;
        j = B.length - 1;
        k = C.length - 1;
        int min_diff, current_diff, max_term;
        min_diff = Math.abs(Math.max(A[i], Math.max(B[j], C[k])) - Math.min(A[i], Math.min(B[j], C[k])));
        while (i >= 0 && j >= 0 && k >= 0) {
            current_diff = Math.abs(Math.max(A[i], Math.max(B[j], C[k])) - Math.min(A[i], Math.min(B[j], C[k])));
            min_diff = Math.min(min_diff, current_diff);
            max_term = Math.max(A[i], Math.max(B[j], C[k]));
            if (A[i] == max_term)
                i--;
            else if (B[j] == max_term)
                j--;
            else
                k--;
        }
        return min_diff;
    }
}

Last updated