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.
Method:
Start from first element of each array, find the next element that will give the smallest difference, and go to that element.
Solution:
Time: O(n) Space: O(1)
public class Solution { public static int solve(ArrayList<Integer> A, ArrayList<Integer> B, ArrayList<Integer> C) { int diff = Integer.MAX_VALUE; int i = 0; int j = 0; int k = 0; while (i < A.size() && j < B.size() && k < C.size()) { int a = A.get(i); int b = B.get(j); int c = C.get(k); // System.out.println("<" + a + ", " + b + ", " + c + ">"); int min = Math.min(a, Math.min(b, c)); int max = Math.max(a, Math.max(b, c)); // System.out.println("<" + min + ", " + max + ">"); // System.out.println("==========================="); if (max - min < diff) { diff = max - min; } int iDiff = Integer.MAX_VALUE; int jDiff = Integer.MAX_VALUE; int kDiff = Integer.MAX_VALUE; if (i + 1 < A.size()) { a = A.get(i + 1); b = B.get(j); c = C.get(k); min = Math.min(a, Math.min(b, c)); max = Math.max(a, Math.max(b, c)); iDiff = max - min; } if (j + 1 < B.size()) { a = A.get(i); b = B.get(j + 1); c = C.get(k); min = Math.min(a, Math.min(b, c)); max = Math.max(a, Math.max(b, c)); jDiff = max - min; } if (k + 1 < C.size()) { a = A.get(i); b = B.get(j); c = C.get(k + 1); min = Math.min(a, Math.min(b, c)); max = Math.max(a, Math.max(b, c)); kDiff = max - min; } if (iDiff <= jDiff && iDiff <= kDiff) { i ++; } else if (jDiff <= iDiff && jDiff <= kDiff) { j ++; } else { k ++; } } return diff; } }