Open In App

Minimum operations of given type to make all elements of a matrix equal

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an integer K and a matrix of N rows and M columns, the task is to find the minimum number of operations required to make all the elements of the matrix equal. In a single operation, K can be added to or subtracted from any element of the matrix. Print -1 if it is impossible to do so.

Examples:

Input: mat[][] = {{2, 4}, {22, 24}}, K = 2 
Output: 20 
Explanation: mat[0][0] = 2 + (10 * K) = 22 … 10 operations 
mat[0][1] = 4 + (9 * K) = 22 … 9 operations 
mat[1][0] = 22 … No operation 
mat[1][1] = 24 – K = 22 … 1 operations 
10 + 9 + 1 = 20 

Input: mat[][] = { 
Explanation: {3, 63, 42}, 
{18, 12, 12}, 
{15, 21, 18}, 
{33, 84, 24}}, 
K = 3 
Output: 63 

Approach: 

  • Since we are only allowed to add or subtract K from any element, we can easily infer that the mod of all the elements with K should be equal because x % K = (x + K) % K = (x – K) % K
  • If that is not the case, simply print -1
  • Otherwise, sort all the elements of the matrix in non-decreasing order and find the median of the sorted elements. 
  • The minimum number of steps would occur if we convert all the elements to equal to the median. 
  • Calculate these steps and print the result.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum
// number of operations required
int minOperations(int n, int m, int k,
                  vector<vector<int> >& matrix)
{
    // Create another array to
    // store the elements of matrix
    vector<int> arr(n * m, 0);
 
    int mod = matrix[0][0] % k;
 
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            arr[i * m + j] = matrix[i][j];
 
            // If not possible
            if (matrix[i][j] % k != mod) {
                return -1;
            }
        }
    }
 
    // Sort the array to get median
    sort(arr.begin(), arr.end());
 
    int median = arr[(n * m) / 2];
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
        minOperations += abs(arr[i] - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0) {
        int median2 = arr[((n * m) / 2) - 1];
        int minOperations2 = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations2 += abs(arr[i] - median2) / k;
 
        minOperations = min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
int main()
{
    vector<vector<int> > matrix = { { 2, 4, 6 },
                                    { 8, 10, 12 },
                                    { 14, 16, 18 },
                                    { 20, 22, 24 } };
    int n = matrix.size();
    int m = matrix[0].size();
    int k = 2;
    cout << minOperations(n, m, k, matrix);
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG {
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m, int k,
                             int matrix[][])
    {
        // Create another array to
        // store the elements of matrix
        int[] arr = new int[n * m];
 
        int mod = matrix[0][0] % k;
 
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr[i * m + j] = matrix[i][j];
 
                // If not possible
                if (matrix[i][j] % k != mod) {
                    return -1;
                }
            }
        }
 
        // Sort the array to get median
        Arrays.sort(arr);
 
        int median = arr[(n * m) / 2];
 
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.abs(arr[i] - median) / k;
 
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
            int median2 = arr[((n * m) / 2) - 1];
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2
                    += Math.abs(arr[i] - median2) / k;
 
            minOperations
                = Math.min(minOperations, minOperations2);
        }
 
        // Return minimum operations required
        return minOperations;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int matrix[][] = { { 2, 4, 6 },
                           { 8, 10, 12 },
                           { 14, 16, 18 },
                           { 20, 22, 24 } };
 
        int n = matrix.length;
        int m = matrix[0].length;
        int k = 2;
        System.out.println(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by ihritik


Python3




# Python3 implementation of the approach
 
# Function to return the minimum
# number of operations required
 
 
def minOperations(n, m, k, matrix):
 
    # Create another array to store the
    # elements of matrix
    arr = [0] * (n * m)
 
    mod = matrix[0][0] % k
 
    for i in range(0, n):
        for j in range(0, m):
            arr[i * m + j] = matrix[i][j]
 
            # If not possible
            if matrix[i][j] % k != mod:
                return -1
 
    # Sort the array to get median
    arr.sort()
 
    median = arr[(n * m) // 2]
 
    # To count the minimum operations
    minOperations = 0
    for i in range(0, n * m):
        minOperations += abs(arr[i] - median) // k
 
    # If there are even elements, then there
    # are two medians. We consider the best
    # of two as answer.
    if (n * m) % 2 == 0:
 
        median2 = arr[((n * m) // 2) - 1]
        minOperations2 = 0
        for i in range(0, n * m):
            minOperations2 += abs(arr[i] - median2) // k
 
        minOperations = min(minOperations,
                            minOperations2)
 
    # Return minimum operations required
    return minOperations
 
 
# Driver code
if __name__ == "__main__":
 
    matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]]
 
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))
 
# This code is contributed by Rituraj Jain


C#




// C# implementation of the approach
using System;
 
class GFG {
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m, int k,
                             int[, ] matrix)
    {
 
        // Create another array to
        // store the elements of matrix
        int[] arr = new int[n * m];
 
        int mod = matrix[0, 0] % k;
 
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr[i * m + j] = matrix[i, j];
 
                // If not possible
                if (matrix[i, j] % k != mod) {
                    return -1;
                }
            }
        }
 
        // Sort the array to get median
        Array.Sort(arr);
 
        int median = arr[(n * m) / 2];
 
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.Abs(arr[i] - median) / k;
 
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
            int median2 = arr[((n * m) / 2) - 1];
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2
                    += Math.Abs(arr[i] - median2) / k;
 
            minOperations
                = Math.Min(minOperations, minOperations2);
        }
 
        // Return minimum operations required
        return minOperations;
    }
 
    // Driver code
    public static void Main()
    {
        int[, ] matrix = { { 2, 4, 6 },
                           { 8, 10, 12 },
                           { 14, 16, 18 },
                           { 20, 22, 24 } };
 
        int n = matrix.GetLength(0);
        int m = matrix.GetLength(1);
        int k = 2;
        Console.WriteLine(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by Ryuga


Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the minimum
    // number of operations required
    function minOperations(n, m, k, matrix)
    {
        // Create another array to
        // store the elements of matrix
        let arr = new Array(n * m);
        arr.fill(0);
      
        let mod = matrix[0][0] % k;
      
        for (let i = 0; i < n; ++i)
        {
            for (let j = 0; j < m; ++j)
            {
                arr[i * m + j] = matrix[i][j];
      
                // If not possible
                if (matrix[i][j] % k != mod)
                {
                    return -1;
                }
            }
        }
      
        // Sort the array to get median
        arr.sort(function(a, b){return a - b});
      
        let median = arr[parseInt((n * m) / 2, 10)];
      
        // To count the minimum operations
        let minOperations = 0;
        for (let i = 0; i < n * m; ++i)
            minOperations += parseInt(Math.abs(arr[i] - median) / k, 10);
      
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0)
        {
          let median2 = arr[parseInt((n * m) / 2, 10)];
          let minOperations2 = 0;
          for (let i = 0; i < n * m; ++i)
              minOperations2 += parseInt(Math.abs(arr[i] - median2) / k, 10);
 
          minOperations = Math.min(minOperations, minOperations2);
        }
      
        // Return minimum operations required
        return minOperations;
    }
     
    // Driver code
    let matrix = [ [ 2, 4, 6 ],
                   [ 8, 10, 12 ],
                   [ 14, 16, 18 ],
                   [ 20, 22, 24 ] ];
 
    let n = 4;
    let m = 3;
    let k = 2;
    document.write(minOperations(n, m, k, matrix));
     
    // This code is contributed by mukesh07.
</script>


Output

36









Minimum operations of given type to make all elements of a Matrix equal with negative numbers

Implementation:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum
// number of operations required
int minOperations(int n, int m, int k,
                  vector<vector<int> >& matrix)
{
    // Create another array to
    // store the elements of matrix
    vector<int> arr;
 
    int mod;
 
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0) {
        mod = k - (abs(matrix[0][0]) % k);
    }
    else {
        mod = matrix[0][0] % k;
    }
 
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            arr.push_back(matrix[i][j]);
 
            // adding this to handle negative elements too .
            int val = matrix[i][j];
            if (val < 0) {
                int res = k - (abs(val) % k);
                if (res != mod) {
                    return -1;
                }
            }
            else {
                int foo = matrix[i][j];
                if (foo % k != mod) {
                    return -1;
                }
            }
        }
    }
 
    // Sort the array to get median
    sort(arr.begin(), arr.end());
 
    int median = arr[(n * m) / 2];
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
        minOperations += abs(arr[i] - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0) {
 
        // changed here as in case of even elements there
        // will be 2 medians
        int median2 = arr[((n * m) / 2) - 1];
 
        int minOperations2 = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations2 += abs(arr[i] - median2) / k;
 
        minOperations = min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
int main()
{
    vector<vector<int> > matrix = { { 2, 4, 6 },
                                    { 8, 10, 12 },
                                    { 14, 16, 18 },
                                    { 20, 22, 24 } };
    int n = matrix.size();
    int m = matrix[0].size();
    int k = 2;
    cout << minOperations(n, m, k, matrix);
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
class GFG {
 
    // Function to return the minimum
    // number of operations required
    public static int minOperations(int n, int m, int k,
                                    int matrix[][])
    {
        // Create another array to
        // store the elements of matrix
        Vector<Integer> arr = new Vector<>();
 
        int mod;
 
        // will not work for negative elements, so ..
        // adding this
        if (matrix[0][0] < 0) {
            mod = k - (Math.abs(matrix[0][0]) % k);
        }
        else {
            mod = matrix[0][0] % k;
        }
 
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr.add(matrix[i][j]);
 
                // adding this to handle
                // negative elements too .
                int val = matrix[i][j];
                if (val < 0) {
                    int res = k - (Math.abs(val) % k);
                    if (res != mod) {
                        return -1;
                    }
                }
                else {
                    int foo = matrix[i][j];
                    if (foo % k != mod) {
                        return -1;
                    }
                }
            }
        }
 
        // Sort the array to get median
        Collections.sort(arr);
        int median = arr.get((n * m) / 2);
 
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations
                += Math.abs(arr.get(i) - median) / k;
 
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
 
            // changed here as in case of
            // even elements there will be 2 medians
            int median2 = arr.get(((n * m) / 2) - 1);
 
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2
                    += Math.abs(arr.get(i) - median2) / k;
 
            minOperations
                = Math.min(minOperations, minOperations2);
        }
 
        // Return minimum operations required
        return minOperations;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int matrix[][] = { { 2, 4, 6 },
                           { 8, 10, 12 },
                           { 14, 16, 18 },
                           { 20, 22, 24 } };
        int n = matrix.length;
        int m = matrix[0].length;
        int k = 2;
        System.out.println(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by divyesh072019


Python3




# Python3 implementation of the
# above approach
 
# Function to return the minimum
# number of operations required
 
 
def minOperations(n, m, k,
                  matrix):
 
    # Create another array to
    # store the elements of
    # matrix
    arr = []
 
    # will not work for negative
    # elements, so .. adding this
    if (matrix[0][0] < 0):
        mod = k - (abs(matrix[0][0]) % k)
    else:
        mod = matrix[0][0] % k
 
    for i in range(n):
        for j in range(m):
            arr.append(matrix[i][j])
 
            # adding this to handle
            # negative elements too .
            val = matrix[i][j]
 
            if (val < 0):
                res = k - (abs(val) % k)
                if (res != mod):
                    return -1
            else:
                foo = matrix[i][j]
                if (foo % k != mod):
                    return -1
 
    # Sort the array to get median
    arr.sort()
 
    median = arr[(n * m) // 2]
 
    # To count the minimum
    # operations
    minOperations = 0
    for i in range(n * m):
        minOperations += abs(arr[i] -
                             median) // k
 
    # If there are even elements,
    # then there are two medians.
    # We consider the best of two
    # as answer.
    if ((n * m) % 2 == 0):
 
        # changed here as in case of
        # even elements there will be
        # 2 medians
        median2 = arr[((n * m) //
                       2) - 1]
 
        minOperations2 = 0
        for i in range(n * m):
            minOperations2 += abs(arr[i] -
                                  median2) / k
 
        minOperations = min(minOperations,
                            minOperations2)
 
    # Return minimum operations required
    return minOperations
 
 
# Driver code
if __name__ == "__main__":
 
    matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]]
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))
 
# This code is contributed by Chitranayal


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG {
 
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m, int k,
                             List<List<int> > matrix)
    {
        // Create another array to
        // store the elements of matrix
        List<int> arr = new List<int>();
 
        int mod;
 
        // will not work for negative elements, so ..
        // adding this
        if (matrix[0][0] < 0) {
            mod = k - (Math.Abs(matrix[0][0]) % k);
        }
        else {
            mod = matrix[0][0] % k;
        }
 
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr.Add(matrix[i][j]);
 
                // adding this to handle negative elements
                // too .
                int val = matrix[i][j];
                if (val < 0) {
                    int res = k - (Math.Abs(val) % k);
                    if (res != mod) {
                        return -1;
                    }
                }
                else {
                    int foo = matrix[i][j];
                    if (foo % k != mod) {
                        return -1;
                    }
                }
            }
        }
 
        // Sort the array to get median
        arr.Sort();
 
        int median = arr[(n * m) / 2];
 
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.Abs(arr[i] - median) / k;
 
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
 
            // changed here as in case of
            // even elements there will be 2 medians
            int median2 = arr[((n * m) / 2) - 1];
 
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2
                    += Math.Abs(arr[i] - median2) / k;
 
            minOperations
                = Math.Min(minOperations, minOperations2);
        }
 
        // Return minimum operations required
        return minOperations;
    }
 
    static void Main()
    {
        List<List<int> > matrix = new List<List<int> >{
            new List<int>{ 2, 4, 6 },
            new List<int>{ 8, 10, 12 },
            new List<int>{ 14, 16, 18 },
            new List<int>{ 20, 22, 24 },
        };
        int n = matrix.Count;
        int m = matrix[0].Count;
        int k = 2;
        Console.Write(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the minimum
// number of operations required
function minOperations(n,m,k,matrix)
{
    // Create another array to
    // store the elements of matrix
    let arr = [];
  
    let mod;
  
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0)
    {
      mod = k - (Math.abs(matrix[0][0]) % k);
    }
    else
    {
      mod = matrix[0][0] % k;
    }
  
    for (let i = 0; i < n; ++i)
    {
      for (let j = 0; j < m; ++j)
      {
        arr.push(matrix[i][j]);
  
        // adding this to handle
        // negative elements too .
        let val = matrix[i][j];
        if (val < 0)
        {
          let res = k - (Math.abs(val) % k);
          if (res != mod)
          {
            return -1;
          }
        }
        else
        {
          let foo = matrix[i][j];
          if (foo % k != mod)
          {
            return -1;
          }
        }
      }
    }
  
    // Sort the array to get median
    arr.sort(function(a,b){return a-b;});    
    let median = arr[(n * m) / 2];
  
    // To count the minimum operations
    let minOperations = 0;
    for (let i = 0; i < n * m; ++i)
      minOperations += Math.abs(arr[i] - median) / k;
  
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0)
    {
  
      // changed here as in case of
      // even elements there will be 2 medians
      let median2 = arr[((n * m) / 2) - 1];
  
      let minOperations2 = 0;
      for (let i = 0; i < n * m; ++i)
        minOperations2 += Math.abs(arr[i] - median2) / k;
  
      minOperations = Math.min(minOperations, minOperations2);
    }
  
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
let matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]];
               
let n = matrix.length;
let m = matrix[0].length;
let k = 2;
document.write(minOperations(n, m, k, matrix));
 
// This code is contributed by rag2127
</script>


Output

36









Complexity Analysis:

  • Time Complexity: O(n*m* log(n*m)), where n is the number of rows and m is the number of columns of the given matrix.
  • Auxiliary Space: O(n*m)

Using Binary Search:

Approach:

We can also use binary search to solve this problem. We can start with the minimum element of the matrix and the maximum element of the matrix as the lower and upper bounds of the binary search. We can then calculate the middle element of the range and count the number of operations required to make all the elements of the matrix equal to the middle element using the given formula. If the number of operations is less than the minimum number of operations seen so far, we update the minimum number of operations. We then update the lower and upper bounds based on whether the middle element is greater than or less than the value we are searching for.

C++




//C++ code for the above approach
#include <iostream>
#include <vector>
#include <algorithm>
#include<climits>
 
using namespace std;
 
int minimumOperations(vector<vector<int>>& mat, int K) {
    int n = mat.size();
    int m = mat[0].size();
    int minVal = INT_MAX;
    int maxVal = INT_MIN;
    for (int i = 0; i < n; i++) {
        minVal = min(minVal, *min_element(mat[i].begin(), mat[i].end()));
        maxVal = max(maxVal, *max_element(mat[i].begin(), mat[i].end()));
    }
    int minOps = INT_MAX;
    while (minVal <= maxVal) {
        int midVal = (minVal + maxVal) / 2;
        int ops = 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] < midVal) {
                    ops += (midVal - mat[i][j]) / K;
                } else {
                    ops += (mat[i][j] - midVal) / K;
                }
            }
        }
        if (ops < minOps) {
            minOps = ops;
        }
        if (midVal == maxVal) {
            break;
        }
        if (ops == (n * m)) {
            break;
        }
        if (ops < (n * m) / 2) {
            maxVal = midVal;
        } else {
            minVal = midVal + 1;
        }
    }
    return minOps;
}
 
int main() {
    vector<vector<int>> mat = { { 2, 4 }, { 22, 24 } };
    int K = 2;
    cout << minimumOperations(mat, K) << endl;
    return 0;
}


Java




import java.util.*;
 
class GFG {
    static int minimumOperations(int[][] mat, int K) {
        int n = mat.length;
        int m = mat[0].length;
        int minVal = Integer.MAX_VALUE;
        int maxVal = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            minVal = Math.min(minVal, Arrays.stream(mat[i]).min().getAsInt());
            maxVal = Math.max(maxVal, Arrays.stream(mat[i]).max().getAsInt());
        }
        int minOps = Integer.MAX_VALUE;
        while (minVal <= maxVal) {
            int midVal = (minVal + maxVal) / 2;
            int ops = 2;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (mat[i][j] < midVal) {
                        ops += (midVal - mat[i][j]) / K;
                    } else {
                        ops += (mat[i][j] - midVal) / K;
                    }
                }
            }
            if (ops < minOps) {
                minOps = ops;
            }
            if (midVal == maxVal) {
                break;
            }
            if (ops == (n * m)) {
                break;
            }
            if (ops < (n * m) / 2) {
                maxVal = midVal;
            } else {
                minVal = midVal + 1;
            }
        }
        return minOps;
    }
 
    public static void main(String[] args) {
        int[][] mat = { { 2, 4 }, { 22, 24 } };
        int K = 2;
        System.out.println(minimumOperations(mat, K));
    }
}


Python3




def minimum_operations(mat, K):
    n = len(mat)
    m = len(mat[0])
    min_val = min(mat[0])
    max_val = max(mat[-1])
    min_ops = float('inf')
    while min_val <= max_val:
        mid_val = (min_val + max_val) // 2
        ops = 2
        for i in range(n):
            for j in range(m):
                if mat[i][j] < mid_val:
                    ops += (mid_val - mat[i][j]) // K
                else:
                    ops += (mat[i][j] - mid_val) // K
        if ops < min_ops:
            min_ops = ops
        if mid_val == max_val:
            break
        if ops == (n * m):
            break
        if ops < (n * m) // 2:
            max_val = mid_val
        else:
            min_val = mid_val + 1
    return min_ops
 
# Sample Input
mat = [[2, 4], [22, 24]]
K = 2
 
# Output: 20
print(minimum_operations(mat, K))


C#




using System;
 
class GFG
{
    static int MinimumOperations(int[][] mat, int K)
    {
        int n = mat.Length;
        int m = mat[0].Length;
        int minVal = int.MaxValue;
        int maxVal = int.MinValue;
        for (int i = 0; i < n; i++)
        {
            minVal = Math.Min(minVal, Array.Find(mat[i], x => x == Array.Find(mat[i], y => true)));
            maxVal = Math.Max(maxVal, Array.Find(mat[i], x => x == Array.Find(mat[i], y => true)));
        }
        int minOps = int.MaxValue;
        while (minVal <= maxVal)
        {
            int midVal = (minVal + maxVal) / 2;
            int ops = 2;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (mat[i][j] < midVal)
                    {
                        ops += (midVal - mat[i][j]) / K;
                    }
                    else
                    {
                        ops += (mat[i][j] - midVal) / K;
                    }
                }
            }
            if (ops < minOps)
            {
                minOps = ops;
            }
            if (midVal == maxVal)
            {
                break;
            }
            if (ops == (n * m))
            {
                break;
            }
            if (ops < (n * m) / 2)
            {
                maxVal = midVal;
            }
            else
            {
                minVal = midVal + 1;
            }
        }
        return minOps;
    }
 
    public static void Main(string[] args)
    {
        int[][] mat = { new int[] { 2, 4 }, new int[] { 22, 24 } };
        int K = 2;
        Console.WriteLine(MinimumOperations(mat, K));
    }
}


Javascript




function minimumOperations(mat, K) {
    const n = mat.length;
    const m = mat[0].length;
    let minVal = Math.min(...mat[0]);
    let maxVal = Math.max(...mat[n - 1]);
    let minOps = Infinity;
 
    while (minVal <= maxVal) {
        const midVal = Math.floor((minVal + maxVal) / 2);
        let ops = 2;
 
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < m; j++) {
                if (mat[i][j] < midVal) {
                    ops += Math.floor((midVal - mat[i][j]) / K);
                } else {
                    ops += Math.floor((mat[i][j] - midVal) / K);
                }
            }
        }
 
        if (ops < minOps) {
            minOps = ops;
        }
 
        if (midVal === maxVal || ops === n * m) {
            break;
        }
 
        if (ops < (n * m) / 2) {
            maxVal = midVal;
        } else {
            minVal = midVal + 1;
        }
    }
 
    return minOps;
}
const mat = [[2, 4], [22, 24]];
const K = 2;
 
console.log(minimumOperations(mat, K));


Output

20









Time Complexity: O(n^2 log(max_val – min_val))
Space Complexity: O(1)



Last Updated : 19 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads