Popular Posts

Thursday, August 18, 2011

|a-b| + |b-c| + |c-a|

Problem:

Given n arrays, find n number such that sum of their differences is minimum. For e.g. if there are three arrays
A = {4, 10, 15, 20}
B = {1, 13, 29}
C = {5, 14, 28}
find three numbers a, b, c such that |a-b| + |b-c| + |c-a| is minimum 

where a E A , bEB , cEC

. Here the answer is a = 15, b = 13, and c = 14


Solution:
Let,
min_dif=INT_MAX
1.Sort the N arrays A,B,C.....
2.Find the minimum and maximum of A[0],B[0],C[0].....
3.Take the difference between MAX-MIN values.
5.If the difference is less than min_dif then update min_dif and save all n values.
6.Now increment the index of the array which contains minimum element.
7.repeat these steps till end of array is reached for atleast one array.


Complexity: O(total no of elements)
Code:


No comments:

Post a Comment