Open In App

Minimum operations required to make each row and column of matrix equals

Improve
Improve
Like Article
Like
Save
Share
Report

Given a square matrix of size N X N. Find a minimum number of operations that are required such that the sum of elements on each row and column becomes equal. In one operation, increment any value of the cell of the matrix by 1. In the first line print the minimum operation required and in the next ‘n’ lines, print ‘n’ integers representing the final matrix after the procedure. 

Example: 

Input: {{1, 2},
           {3, 4}}
Output: 4
              {{4, 3}, 
              {3, 4}}
Explanation: Increment value of cell(0, 0) by 3. 
                       Increment value of cell(0, 1) by 1
                      Hence total 4 operation are required

Input: {{1, 2, 3},
            {4, 2, 3},
           {3, 2, 1}}
Output: 6
              {{2, 4, 3}, 
              {4, 2, 3}, 
             {3, 3, 3}} 
Explanation: Increment value of cell(0, 0) by 1. 
                       Increment value of cell(0, 1) by 2. 
                       Increment value of cell(2, 1) by 1.
                       Increment value of cell(2, 2) by 2.
                       Hence total 6 operation are required  

Recommended Practice

Minimum operations required to make each row and column of the matrix equals using Two arrays:

The idea is to calculate the maximum sum of each row and each column. And then perform operations on the rows and cols which has sum less than maximum calculated sum.

Follow the steps below to solve the problem:

  • Let’s assume that maxSum is the maximum sum among all rows and columns. We just need to increment some cells such that the sum of any row or column becomes ‘maxSum’. 
  • Let’s say Xi is the total number of operations needed to make the sum on row ‘i’ equals to maxSum and Yj is the total number of operations needed to make the sum on column ‘j’ equal to maxSum
  • Since Xi = Yj so we need to work at any one of them according to the condition.
  • In order to minimize Xi, we need to choose the maximum from rowSumi and colSumj as it will surely lead to minimum operation. After that, increment ‘i’ or ‘j’ according to the condition satisfied after the increment.

Below is the implementation of the above approach.

C++




// C++ Program to Find minimum number of operation required
// such that sum of elements on each row and column becomes
// same*/
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum operation required to make sum
// of each row and column equals
int findMinOpeartion(int matrix[][2], int n)
{
    // Initialize the sumRow[] and sumCol[] array to 0
    int sumRow[n], sumCol[n];
    memset(sumRow, 0, sizeof(sumRow));
    memset(sumCol, 0, sizeof(sumCol));
    // Calculate sumRow[] and sumCol[] array
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j) {
            sumRow[i] += matrix[i][j];
            sumCol[j] += matrix[i][j];
        }
    // Find maximum sum value in either row or in column
    int maxSum = 0;
    for (int i = 0; i < n; ++i) {
        maxSum = max(maxSum, sumRow[i]);
        maxSum = max(maxSum, sumCol[i]);
    }
    int count = 0;
    for (int i = 0, j = 0; i < n && j < n;) {
        // Find minimum increment required in either row or
        // column
        int diff
            = min(maxSum - sumRow[i], maxSum - sumCol[j]);
        // Add difference in corresponding cell, sumRow[]
        // and sumCol[] array
        matrix[i][j] += diff;
        sumRow[i] += diff;
        sumCol[j] += diff;
        // Update the count variable
        count += diff;
        // If ith row satisfied, increment ith value for
        // next iteration
        if (sumRow[i] == maxSum)
            ++i;
        // If jth column satisfied, increment jth value for
        // next iteration
        if (sumCol[j] == maxSum)
            ++j;
    }
    return count;
}
 
// Utility function to print matrix
void printMatrix(int matrix[][2], int n)
{
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j)
            cout << matrix[i][j] << " ";
        cout << "\n";
    }
}
 
// Driver code
int main()
{
    int matrix[][2] = { { 1, 2 }, { 3, 4 } };
    cout << findMinOpeartion(matrix, 2) << "\n";
    printMatrix(matrix, 2);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C Program to Find minimum number of operation required
// such that sum of elements on each row and column becomes
// same
#include <stdio.h>
#include <string.h>
 
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
 
// Find minimum between two numbers.
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
// Function to find minimum operation required to make sum
// of each row and column equals
int findMinOpeartion(int matrix[][2], int n)
{
    // Initialize the sumRow[] and sumCol[] array to 0
    int sumRow[n], sumCol[n];
    memset(sumRow, 0, sizeof(sumRow));
    memset(sumCol, 0, sizeof(sumCol));
 
    // Calculate sumRow[] and sumCol[] array
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j) {
            sumRow[i] += matrix[i][j];
            sumCol[j] += matrix[i][j];
        }
 
    // Find maximum sum value in either row or in column
    int maxSum = 0;
    for (int i = 0; i < n; ++i) {
        maxSum = max(maxSum, sumRow[i]);
        maxSum = max(maxSum, sumCol[i]);
    }
 
    int count = 0;
    for (int i = 0, j = 0; i < n && j < n;) {
 
        // Find minimum increment required in either row or
        // column
        int diff
            = min(maxSum - sumRow[i], maxSum - sumCol[j]);
 
        // Add difference in corresponding cell, sumRow[]
        // and sumCol[] array
        matrix[i][j] += diff;
        sumRow[i] += diff;
        sumCol[j] += diff;
 
        // Update the count variable
        count += diff;
 
        // If ith row satisfied, increment ith value for
        // next iteration
        if (sumRow[i] == maxSum)
            ++i;
 
        // If jth column satisfied, increment jth value for
        // next iteration
        if (sumCol[j] == maxSum)
            ++j;
    }
    return count;
}
 
// Utility function to print matrix
void printMatrix(int matrix[][2], int n)
{
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j)
            printf("%d ", matrix[i][j]);
        printf("\n");
    }
}
 
// Driver code
int main()
{
    int matrix[][2] = { { 1, 2 }, { 3, 4 } };
    printf("%d\n", findMinOpeartion(matrix, 2));
    printMatrix(matrix, 2);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java Program to Find minimum number of operation required
// such that sum of elements on each row and column becomes
// same
import java.io.*;
 
class GFG {
 
    // Function to find minimum operation required to make
    // sum of each row and column equals
    static int findMinOpeartion(int matrix[][], int n)
    {
        // Initialize the sumRow[] and sumCol[] array to 0
        int[] sumRow = new int[n];
        int[] sumCol = new int[n];
        // Calculate sumRow[] and sumCol[] array
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < n; ++j) {
                sumRow[i] += matrix[i][j];
                sumCol[j] += matrix[i][j];
            }
        // Find maximum sum value in either row or in column
        int maxSum = 0;
        for (int i = 0; i < n; ++i) {
            maxSum = Math.max(maxSum, sumRow[i]);
            maxSum = Math.max(maxSum, sumCol[i]);
        }
        int count = 0;
        for (int i = 0, j = 0; i < n && j < n;) {
            // Find minimum increment required in either row
            // or column
            int diff = Math.min(maxSum - sumRow[i],
                                maxSum - sumCol[j]);
            // Add difference in corresponding cell,
            // sumRow[] and sumCol[] array
            matrix[i][j] += diff;
            sumRow[i] += diff;
            sumCol[j] += diff;
            // Update the count variable
            count += diff;
            // If ith row satisfied, increment ith value for
            // next iteration
            if (sumRow[i] == maxSum)
                ++i;
            // If jth column satisfied, increment jth value
            // for next iteration
            if (sumCol[j] == maxSum)
                ++j;
        }
        return count;
    }
 
    // Utility function to print matrix
    static void printMatrix(int matrix[][], int n)
    {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j)
                System.out.print(matrix[i][j] + " ");
            System.out.println();
        }
    }
 
    /* Driver program */
    public static void main(String[] args)
    {
        int matrix[][] = { { 1, 2 }, { 3, 4 } };
        System.out.println(findMinOpeartion(matrix, 2));
        printMatrix(matrix, 2);
    }
}
 
// This code is contributed by Sania Kumari Gupta


Python 3




# Python 3 Program to Find minimum
# number of operation required such
# that sum of elements on each row
# and column becomes same
 
# Function to find minimum operation
# required to make sum of each row
# and column equals
 
 
def findMinOpeartion(matrix, n):
 
    # Initialize the sumRow[] and sumCol[]
    # array to 0
    sumRow = [0] * n
    sumCol = [0] * n
 
    # Calculate sumRow[] and sumCol[] array
    for i in range(n):
        for j in range(n):
            sumRow[i] += matrix[i][j]
            sumCol[j] += matrix[i][j]
 
    # Find maximum sum value in
    # either row or in column
    maxSum = 0
    for i in range(n):
        maxSum = max(maxSum, sumRow[i])
        maxSum = max(maxSum, sumCol[i])
 
    count = 0
    i = 0
    j = 0
    while i < n and j < n:
 
        # Find minimum increment required
        # in either row or column
        diff = min(maxSum - sumRow[i],
                   maxSum - sumCol[j])
 
        # Add difference in corresponding
        # cell, sumRow[] and sumCol[] array
        matrix[i][j] += diff
        sumRow[i] += diff
        sumCol[j] += diff
 
        # Update the count variable
        count += diff
 
        # If ith row satisfied, increment
        # ith value for next iteration
        if (sumRow[i] == maxSum):
            i += 1
 
        # If jth column satisfied, increment
        # jth value for next iteration
        if (sumCol[j] == maxSum):
            j += 1
 
    return count
 
# Utility function to print matrix
 
 
def printMatrix(matrix, n):
    for i in range(n):
        for j in range(n):
            print(matrix[i][j], end=" ")
        print()
 
 
# Driver code
if __name__ == "__main__":
    matrix = [[1, 2],
              [3, 4]]
    print(findMinOpeartion(matrix, 2))
    printMatrix(matrix, 2)
 
# This code is contributed
# by ChitraNayal


C#




// C# Program to Find minimum
// number of operation required
// such that sum of elements on
// each row and column becomes same
using System;
 
class GFG {
 
    // Function to find minimum
    // operation required
    // to make sum of each row
    // and column equals
    static int findMinOpeartion(int[, ] matrix, int n)
    {
        // Initialize the sumRow[]
        // and sumCol[] array to 0
        int[] sumRow = new int[n];
        int[] sumCol = new int[n];
 
        // Calculate sumRow[] and
        // sumCol[] array
        for (int i = 0; i < n; ++i)
 
            for (int j = 0; j < n; ++j) {
                sumRow[i] += matrix[i, j];
                sumCol[j] += matrix[i, j];
            }
 
        // Find maximum sum value
        // in either row or in column
        int maxSum = 0;
        for (int i = 0; i < n; ++i) {
            maxSum = Math.Max(maxSum, sumRow[i]);
            maxSum = Math.Max(maxSum, sumCol[i]);
        }
 
        int count = 0;
        for (int i = 0, j = 0; i < n && j < n;) {
            // Find minimum increment
            // required in either row
            // or column
            int diff = Math.Min(maxSum - sumRow[i],
                                maxSum - sumCol[j]);
 
            // Add difference in
            // corresponding cell,
            // sumRow[] and sumCol[]
            // array
            matrix[i, j] += diff;
            sumRow[i] += diff;
            sumCol[j] += diff;
 
            // Update the count
            // variable
            count += diff;
 
            // If ith row satisfied,
            // increment ith value
            // for next iteration
            if (sumRow[i] == maxSum)
                ++i;
 
            // If jth column satisfied,
            // increment jth value for
            // next iteration
            if (sumCol[j] == maxSum)
                ++j;
        }
        return count;
    }
 
    // Utility function to
    // print matrix
    static void printMatrix(int[, ] matrix, int n)
    {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j)
                Console.Write(matrix[i, j] + " ");
 
            Console.WriteLine();
        }
    }
 
    /* Driver program */
    public static void Main()
    {
        int[, ] matrix = { { 1, 2 }, { 3, 4 } };
 
        Console.WriteLine(findMinOpeartion(matrix, 2));
        printMatrix(matrix, 2);
    }
}
 
// This code is contributed by Vt_m.


Javascript




<script>
// Javascript Program to Find minimum
// number of operation required
// such that sum of elements on
// each row and column becomes same
     
    // Function to find minimum
    // operation required
    // to make sum of each row
    // and column equals
    function findMinOpeartion(matrix,n)
    {
        // Initialize the sumRow[]
        // and sumCol[] array to 0
        let sumRow = new Array(n);
        let sumCol = new Array(n);
        for(let i=0;i<n;i++)
        {   
            sumRow[i]=0;
            sumCol[i]=0;
        }
           
        // Calculate sumRow[] and
        // sumCol[] array
        for (let i = 0; i < n; ++i)
    
            for (let j = 0; j < n; ++j)
            {
                sumRow[i] += matrix[i][j];
                sumCol[j] += matrix[i][j];
            }
       
        // Find maximum sum value
        // in either row or in column
        let maxSum = 0;
        for (let i = 0; i < n; ++i)
        {
            maxSum = Math.max(maxSum, sumRow[i]);
            maxSum = Math.max(maxSum, sumCol[i]);
        }
       
        let count = 0;
        for (let i = 0, j = 0; i < n && j < n;)
        {
            // Find minimum increment
            // required in either row
            // or column
            let diff = Math.min(maxSum - sumRow[i],
                        maxSum - sumCol[j]);
       
            // Add difference in
            // corresponding cell,
            // sumRow[] and sumCol[]
            // array
            matrix[i][j] += diff;
            sumRow[i] += diff;
            sumCol[j] += diff;
       
            // Update the count
            // variable
            count += diff;
       
            // If ith row satisfied,
            // increment ith value
            // for next iteration
            if (sumRow[i] == maxSum)
                ++i;
       
            // If jth column satisfied,
            // increment jth value for
            // next iteration
            if (sumCol[j] == maxSum)
                ++j;
        }
        return count;
    }
     
    // Utility function to
    // print matrix
    function printMatrix(matrix,n)
    {
         for (let i = 0; i < n; ++i)
        {
            for (let j = 0; j < n; ++j)
                document.write(matrix[i][j] +
                                           " ");
            
            document.write("<br>");
        }
    }
     
    /* Driver program */
    let matrix=[[1, 2],[3, 4]];
    document.write(findMinOpeartion(matrix, 2)+"<br>");
    printMatrix(matrix, 2);
    // This code is contributed by avanitrachhadiya2155
</script>


Output

4
4 3 
3 4 

Time complexity: O(N2), Traversing the matrix for calculating sum of each row and each column
Auxiliary space: O(N), Storing the sum of each row and each column.



Last Updated : 07 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads