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

C++Server Side ProgrammingProgramming

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], , [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)

• increase last element of temp

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

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

• temp := lists[temp, 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 < b);
}
};
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], i, 0});
maxVal = max(lists[i], maxVal);
}
while (pq.size() == n) {
vector<int> temp = pq.top();
pq.pop();
ret = min(ret, maxVal - temp);
temp.back()++;
if (temp.back() < lists[temp].size()) {
maxVal = max(maxVal, lists[temp][temp.back()]);
temp = lists[temp][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