Wednesday, August 9th
Min the max pair diff
Given an integer array and integer p, find p pairs of indices such that the maximum difference among all of them is minimized
Despite what is given in the hint, this problem is not to be solved with dynamic programming
Instead, we will take a greedy approach coupled with binary search
The idea is we can use binary search to tests different thresholds. The thresholds represent maximum differences between pairs, and we calculate how many pairs fall below this threshold and compare against p.
First we sort the values, which will help finding minimum differences between pairs
Then we test thresholds. Given a threshold, we iterate over all pairs and test if their difference is below the threshold. If so, we increment c. If a pair is found, we increment i the index so we don't have two pairs using the same value. The return value is how many pairs can be found with differences between the given threshold.
Then we implement binary search. The leftmost index starts at 0, the lowest threshold, while the right, or the maximum threshold, is the largest difference possible (since values are sorted).
Once binary search is executed, it calls the threshold test function with the midpoint. At each iteration we update left or right depending on whether p pairs could be found for a given threshold. In the end, the left value +1 will be smallest threshold where p pairs could be found.
Another application of binary search
Thanks to vanAmsen for binary search details and interesting comparison of language runtime statistics
Comments
Post a Comment