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]);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement