Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- The modulo of all elements with x must be same,otherwise you won't be able to make all elements
- same.
- push all elements in one grid,sort them and find the median.Then summation of absolute difference/x
- will be the answer.
- Answer on both median will be same in case of even number of elements in grid.
- */
- int calculate_operations(vector <int> arr,int x,int mid){
- int ans=0;
- for(int i=0;i<arr.size();i++){
- if((mid-arr[i])%x!=0)return -1;
- ans+=abs((mid-arr[i])/x);
- }
- return ans;
- }
- class Solution {
- public:
- int minOperations(vector<vector<int>>& grid, int x) {
- vector <int> arr;
- for(auto itr:grid){
- for(auto it:itr)
- arr.push_back(it);
- }
- if(arr.size()==1) return 0;
- sort(arr.begin(),arr.end());
- return calculate_operations(arr,x,arr[arr.size()/2]);
- }
- };
- #Python
- class Solution:
- def minOperations(self, grid: List[List[int]], x: int) -> int:
- arr=[]
- val=-1
- for i in grid:
- for j in i:
- if val==-1:
- val=j%x
- arr.append(j)
- elif j%x!=val:
- return -1
- else:
- arr.append(j)
- arr=sorted(arr)
- val=arr[len(arr)//2]
- ans=0
- for i in arr:
- ans+=abs(val-i)//x
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement