Cool JAVA Solution

Tags: #<Tag:0x00007f2426fb6de0>


public class Solution {
public int solve(int[] A, int[] B, int[] C) {
int min = Integer.MAX_VALUE,tempMin;

    for(int i=0; i<A.length; i++){
        for(int j=0; j<B.length; j++){
            if(Math.abs(A[i]-B[j]) > min)
            for(int k=0; k<C.length; k++){
                if(Math.abs(C[k]-B[j]) > min)
                tempMin = findMin(A[i],B[j],C[k]);
                if(tempMin < min)
                    min = tempMin;
    return min;

public int findMin(int a, int b, int c){
    int min=a,max=a;
    if(a>=b && a>=c)
        max = a;
    if(b>=a && b>=c)
        max = b;
    if(c>=a && c>=b)
        max = c;
    if(a<=b && a<=c)
        min = a;
    if(b<=a && b<=c)
        min = b;
    if(c<=a && c<=b)
        min = c;
    return Math.abs(max-min);    



Can you please explain the approach you have followed in detail.


Simple approach. 3 for loop to loop through 3 arrays and consider every triplet.
The findMin() function to calculate min and max for each triplet.
‘min’ is to store the min absolute diff till now.
And the if conditions are to optimize the loops i.e. if already 2 elements are making abs diff more than the ‘min’ we don’t need to go further with these elements.


Its complexity is n^3 I guess. If its right, then its not that cool, its just brute force.

I implemented something different using single while loop, It was a guess but it worked.

public class Solution {
public int solve(ArrayList A, ArrayList B, ArrayList C) {
int a1=0;
int b1=0;
int c1=0;

    int minAbs=Integer.MAX_VALUE;
    while(a1<A.size() && b1<B.size() && c1<C.size())
        int min=Math.min(A.get(a1),Math.min(B.get(b1),C.get(c1)));
        int max=Math.max(A.get(a1),Math.max(B.get(b1),C.get(c1)));
        int abs=Math.abs(max-min);
        else if(min==B.get(b1))
    return minAbs;