Advertisement
imashutosh51

Minimum Operations to Make a Uni-Value Grid

Jun 19th, 2023
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. /*
  2. Logic:
  3. The modulo of all elements with x must be same,otherwise you won't be able to make all elements
  4. same.
  5. push all elements in one grid,sort them and find the median.Then summation of absolute difference/x
  6. will be the answer.
  7. Answer on both median will be same in case of even number of elements in grid.
  8. */
  9. int calculate_operations(vector <int> arr,int x,int mid){
  10.     int ans=0;
  11.     for(int i=0;i<arr.size();i++){
  12.         if((mid-arr[i])%x!=0)return -1;
  13.         ans+=abs((mid-arr[i])/x);
  14.     }  
  15.     return ans;
  16. }
  17.  
  18. class Solution {
  19. public:
  20.     int minOperations(vector<vector<int>>& grid, int x) {
  21.         vector <int> arr;
  22.         for(auto itr:grid){
  23.             for(auto it:itr)
  24.                arr.push_back(it);
  25.         }
  26.         if(arr.size()==1) return 0;
  27.         sort(arr.begin(),arr.end());
  28.         return calculate_operations(arr,x,arr[arr.size()/2]);
  29.     }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement