RainX_69

COMPANY INTERVIEW PROBLEM

Feb 9th, 2023
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | Source Code | 0 0
  1. Given a 2d array, choose one element from each row such that final array has lowest difference between maximum and minimum elements of final array. Returrn sorted final array.
  2.  
  3. Ex: Input : [[61,90,60], [59,61],[58,62,92]]
  4. OutPut: [61,61,62]
  5.  
  6. ---------------------------------------------------------------------------------------------------------------------------------------
  7.  
  8. #include<bits/stdc++.h>
  9. using namespace std;
  10.  
  11. #define PAIR pair<int,int>
  12.  
  13. void solve(vector<vector<int>> &arr){
  14.    
  15.     for(auto &vec: arr){
  16.         sort(vec.begin(),vec.end());
  17.     }
  18.    
  19.     priority_queue<pair<int,PAIR>,vector<pair<int,PAIR>>,greater<pair<int,PAIR>>> pq,res;
  20.  
  21.     int mx=INT_MIN;
  22.     int mnDiff=INT_MAX;
  23.  
  24.     for(int i=0;i<arr.size();i++){
  25.         mx=max(arr[i][0],mx);
  26.         pq.push({arr[i][0],{i,0}});
  27.     }
  28.    
  29.     res=pq;
  30.     mnDiff=mx-pq.top().first;
  31.  
  32.     while(!pq.empty()){
  33.         auto info=pq.top();
  34.         pq.pop();
  35.  
  36.         int data=info.first;
  37.         int x=info.second.first;
  38.         int y=info.second.second;        
  39.  
  40.         if(y+1<arr[x].size()){
  41.             mx=max(arr[x][y+1],mx);  // update mx in the process, cuz min is always on top of heap, but you'll lose max if not stored
  42.             pq.push({arr[x][y+1],{x,y+1}});
  43.         }
  44.         else{
  45.             break;
  46.         }
  47.        
  48.         if(mx-pq.top().first<mnDiff){  // checking if diff be made smaller
  49.             res=pq;  // store the current state of priority queue
  50.             mnDiff=mx-pq.top().first;  // updating
  51.         }
  52.     }
  53.    
  54.     while(!res.empty()){  // LET IT PRINT
  55.         cout<<res.top().first<<" ";
  56.         res.pop();
  57.     }
  58.     return;
  59. }
  60.  
  61.  
  62. int main(){
  63.     vector<vector<int>> arr={{61,90,60},{59,61},{58,62,92}};
  64.     solve(arr);  // 61 61 62
  65.    
  66.     // vector<vector<int>> arr={{23,90,60},{59,61},{58,62,92}};
  67.     // solve(arr);  // 58 59 60
  68. }
  69.  
  70.  
  71. A bit similar question -https://leetcode.com/problems/merge-k-sorted-lists/
  72.  
Advertisement
Add Comment
Please, Sign In to add comment