Google Interview Question
Software Engineer / Developerstake diff from k for each number O(n) and then sort the numbers O(n log n)..then we can get the soln in O(k).
k < n < n log n...therefore overall order O(n log n)
What does "take diff from k" mean? Let the N numbers be a1, a2...aN. Are you talking about computing a1-k, a2-k ... aN-k? But I think the problem is about selecting k numbers among a1..aN. I cannot see how this can be solved in O(nlogn).
will sorting the numbers first and choosing the numbers from both ends in pairs give the maximum difference?
For example, suppose we have 5 numbers, 1, 8, 12, 16, 20 (sorted), when k=2, we can choose: 1 and 20, because they give the maximum distance. When k=3, we can choose any numbers in 8, 12, and 16, because 1, 20, and this number give the same total difference. When k=4, if we want to get the maximum difference, the 3rd number has to be 8, so the 4th can be chosen as 16, which has the greatest difference from 8, but not 12.
You got the idea. If we were to choose k numbers, if:
1) k is odd, we choose (k-1)/2 from both ends, and then choose the median.
2) k is even, we choose k/2 from both ends.
This sounds naive. But it seems to work. Complexity would be O(nlgn) for initial sorting.
Sort the sequence {a1,a2,....an-1,an}
Obviously k<=n
keep pointers at a1 and an
now .. if an - a2 > an-1 - a1 choose a2 else choose a1 (accordingly move the pointer)
keep choosing until u have k numbers
consider the nos 1,4,6,19,20 aftr sorting
if k=3 then acc to your algo u'll select 1,19,20
the quest says "the minimum difference of all the possible pairs of k numbers" so the min diff is 1 for 19 & 20
Acc to me you should select 1,6,20... 6 coz center of remaining and one can build on logic from here onwards
1. First sort the array A
2. Then solve this problem using DP as follows:
Let f(i, j) denote, maximum difference if you select i numbers from the array, starting from index j and element at index j must be selected.
f(i, j) = max { min( f(i-1, m), A[m]-A[j] ) }, m=j+1 to n-1, if i<=n-j
f(i, j) = -Infinity, if i >n-j
the goal is to solve f(1, k), (note: it is always safe to include 1st element in the k numbers), complexity is O(n^2)
Sort the array.
- Gopal June 22, 2010Consider a line-segment starting from (A[0],0) and ending at (A[n-1],0). Divide this line-segment into k-2 equal pieces. Find out the closest values to those pieces in the array A - these k values are the answer.