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
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
5 comments :
The solution is given @
http://www.careercup.com/question?id=9582840
by anantha krishnan
@codeninja..i think two approaches are nearly same while i presented from scratch . link u have mentioned presumed array are sorted ..but both leads to to the same solution
do notify me if anything wrong ?
shashank
Your Solution is more elegant and it can be extendable to if there are k arrays . so i would go with your solution. Here the main idea is to find , finding the minimum range among all the elements .
I assume the same solution can be extendable to the below question as well . please let me know your thoughts
given ‘k’ sorted arrays with ‘n’ elements in each array.
Select a number from each array such the range of selected elements is minimum
Range of set of elemets max(selected set)-min(selected set)
is minimum.
Your Solution is more elegant and it can be extendable to if there are k arrays . so i would go with your solution. Here the main idea is to find , finding the minimum range among all the elements .
I assume the same solution can be extendable to the below question as well . please let me know your thoughts
given ‘k’ sorted arrays with ‘n’ elements in each array.
Select a number from each array such the range of selected elements is minimum
Range of set of elemets max(selected set)-min(selected set)
is minimum.
Hi Shashank,
I have got a bit different approach. Please give ur comment on it
1. Sort all the 3 Array.
2. Merge the 3 Arrays such that each element in the MergedArray is a tuple(value, ArrayNum) where ArrayNum = 1/2/3 and value is value the element posses in the original array.
3. Now in the merged array find the sequence such that Element of Array 1, 2 and 3 has mininum distance.
Post a Comment