Solution: [*will re-edit later*]
Basically, the selection depends on the how "wide" the gap we use. If we use the gap as wide as A[n-1] - A[0] (n is the size of array), we can only select 2 elements. On the other way, if we choose the gap as min(A[i+1]-A[i]), we will select n elements. Our goal is to select k elements while with maximized minimum difference. k is within 2 and n. Then a binary search can help us find k.We just do binary search on the space of the width of the gap. We set low = min(A[i+1]-A[i]), high = A[n-1] - A[0] and make mid = (low + high) /2.With this mid as the width of the gap, we can calculate the number of elements we selected. If it is larger than k, we need to increase the width of the gap: we just update low = mid; Otherwise, we need to decrease the width of the gap by update high = mid.We stop when we find a gap such that if we further increase the gap, we can't be able to select k elements.- Try to calculate m[i][j][k], where i and j are the index within A[] and k how many elements are selected with in the region A[i] ~ A[j]. The time to calculate this array is O(N^4).
please give example to this question...didnt get the question.....using word minimum , maximum together is confusing me.
ReplyDeletewe need to find k elements and your algo says
ReplyDelete/*
If it is larger than k, we need to increase the width of the gap: we just update low = mid; Otherwise, we need to decrease the width of the gap by update high = mid.
*/
how can we use k ...if we dont knw value of k.
could you please clear my doubt.
Example updated in the original post. For your question, if we have an array of the length 10 and the k we want is 4 (we want to find 4 elements with maximum minimum consecutive difference). The key is to decide the gap. We start with k=2 and k=10. It is easy to get the value of gap when k equals these two values. The gap when k=2 is the biggest gap and the gap when k=10 is the smallest. Then we can start binary search. We make gap = (gap_k2 + gap_k10)/2. This will return a new value of k.
Delete