Monday, June 20, 2011

Given 3 arrays, pick 3 nos, one from each array, say a,b,c such that |a-b|+|b-c|+|c-a| is minimum

Data Structure Used: Arrays of Integer

Algorithm:
1.Sort all 3 arrays (Using Heap or Quick Sort) , take min = INFINITY
2.Take pointer to start of all the three arrays
3.compute sum = |a-b|+|b-c|+|c-a| where a,b,c are elements pointed to by d pointers
4.if sum < min then sum = min.save a,b,c too 5.increment the pointer of (min (a,b,c)) 6. if not the end of any array. repeat from step 3 Working Code:Java class QuickSort { static int min(int a, int b, int c) { int m = a; if (m > b) m = b;
if (m > c) m = c;
return m;
}


static int findMinof_abc(int a[],int m,int b[],int n,int c[],int l)
{

int min = Integer.MAX_VALUE;
int i = 0, j = 0, k = 0;

while( i < m && j < n && k < l) { n = Math.abs(a[i]- b[j]) + Math.abs(b[j] - c[k])+ Math.abs(c[k] - a[i]); min = n pivot)
j--;
if (i <= j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}

public int[] sort(int[] input)
{
quickSort(input, 0, input.length-1);
return input;
}

public static void main(String args[])
{

QuickSort mNew = new QuickSort();

int a[]={11,13,22,31};
int b[]={18,26,36};
int c[]={28,29,30,33};
mNew.sort(a);
mNew.sort(b);
mNew.sort(c);

int x=4,y=3,z=4;
System.out.println(findMinof_abc(a,x,b,y,c,z));

}


Time Complexity O(NlogN)
Space Complexity O(logN)
Run Here http://ideone.com/eCrlJ