Advertisement
imashutosh51

Minimum Operations to Make a Uni-Value Grid

Jun 19th, 2023 (edited)
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 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. };
  31.  
  32. #Python
  33. class Solution:
  34.     def minOperations(self, grid: List[List[int]], x: int) -> int:
  35.         arr=[]
  36.         val=-1
  37.         for i in grid:
  38.             for j in i:
  39.                 if val==-1:
  40.                     val=j%x
  41.                     arr.append(j)
  42.                 elif j%x!=val:
  43.                     return -1
  44.                 else:
  45.                     arr.append(j)
  46.         arr=sorted(arr)
  47.         val=arr[len(arr)//2]
  48.         ans=0
  49.         for i in arr:
  50.             ans+=abs(val-i)//x
  51.         return ans
  52.  
  53.        
  54.  
  55.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement