Program to find smallest difference between picked elements from different lists in C++


Suppose we have a list of lists, we have to find the smallest difference that can be formed by picking one value from each of the lists and taking the difference between the maximum and the minimum number of the picked element.

So, if the input is like lists = [ [30, 50, 90], [85], [35, 70]], then the output will be 20, as we can take 90, 85, 70 and 90 - 70 = 20

To solve this, we will follow these steps −

  • maxVal := -inf

  • ret := inf

  • define a priority queue pq

  • n := size of lists

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • sort the array lists[i]

    • insert {lists[i, 0], i, 0} into pq

    • maxVal := maximum of lists[i, 0] and maxVal

  • while size of pq is same as n, do −

    • Define an array temp = top of pq

    • delete top element from pq

    • ret := minimum of ret and (maxVal - temp[0])

    • increase last element of temp

    • if last element of temp < size of lists[temp[1]], then <

      • maxVal := maximum of maxVal and lists[temp[1], last element of temp]

      • temp[0] := lists[temp[1], last element of temp]

      • insert temp into pq

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Cmp {
   bool operator()(vector<int>& a, vector<int>& b) {
      return !(a[0] < b[0]);
   }
};
class Solution {
   public:
   int solve(vector<vector<int>>& lists) {
      int maxVal = INT_MIN;
      int ret = INT_MAX;
      priority_queue<vector<int>, vector<vector<int>>, Cmp> pq;
      int n = lists.size();
      for (int i = 0; i < n; i++) {
         sort(lists[i].begin(), lists[i].end());
         pq.push({lists[i][0], i, 0});
         maxVal = max(lists[i][0], maxVal);
      }
      while (pq.size() == n) {
         vector<int> temp = pq.top();
         pq.pop();
         ret = min(ret, maxVal - temp[0]);
         temp.back()++;
         if (temp.back() < lists[temp[1]].size()) {
            maxVal = max(maxVal, lists[temp[1]][temp.back()]);
            temp[0] = lists[temp[1]][temp.back()];
            pq.push(temp);
         }
      }
      return ret;
   }
};
int solve(vector<vector<int>>& lists) {
   return (new Solution())->solve(lists);
}
int main(){
   vector<vector<int>> v = {{30, 50, 90},{85},{35, 70}};
   cout << solve(v);
}

Input

{{30, 50, 90},{85},{35, 70}}

Output

20

Updated on: 23-Dec-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements