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

    int minimizeMax(vector<int>& nums, int p) {
    sort(nums.begin(), nums.end());
        ...
    }       

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 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.

int tt(vector<int>& nums, int t) {
int i=0, c=0;
for(int i=0; i<nums.size()-1; i++) {
if(nums[i+1]-nums[i] <= t) {
c++; i++;
}
}
return c;
}

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.

int minimizeMax(vector<int>& nums, int p) {
        ...        

    int n=nums.size();
    int l=0, r=nums[n-1]-nums[0];
        int mid;

while (l<=r) {
mid=l+(r-l)/2;
if(tt(nums, mid) >= p) {
r=mid+1;
} else {
l=mid+1;
}
}
return l;
}

Another application of binary search

Thanks to vanAmsen for binary search details and interesting comparison of language runtime statistics

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th