Open In App

Making Row and Column Sums Equal

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a square matrix of size n x n, the task is to find minimum number of operations that are required such that the sum of elements on each row and column becomes equal.

In one operation, we can increment any value at any cell of the matrix by 1.

Examples: 

Input: mat[][] = [[1, 2], [3, 4]]
Output: 4
Explanation:

  • Increment value of cell (0, 0) 3 times
  • Increment value of cell (0, 1) 1 time.

Matrix after the operations: [[4, 3], [3, 4]] with sum of each row and column as 7. Hence total 4 operation are required.

Input: mat[][] = [[1, 2, 3], [4, 2, 3], [3, 2, 1]]
Output: 6
Explanation:

  • Increment value of cell(0, 0) 1 time
  • Increment value of cell(0, 1) 2 times
  • Increment value of cell(2, 1) 1 time.
  • Increment value of cell(2, 2) 2 times.

Matrix after the operations: [[2, 4, 3], [4, 2, 3], [3, 3, 3]] with sum of each row and column as 9. Hence total 6 operation are required.

Approach:

The idea is to find the maximum sum among all row and column sums. Now to minimize the operation count, make all row and column sums equal to maximum sum by performing operations on the rows and cols which has sum less than maximum sum.

Now incrementing an element will increase the row sum as well as the column sum, so minimum operations will be equal to the sum of operations for all rows (or columns).

C++
// C++ program to find minimum operation required to the
// make sum of each row and column equals

#include <iostream>
#include <vector>
using namespace std;

int findMinOperation(vector<vector<int>> &mat) {
	int n = mat.size();
    int res = 0;
    int maxSum = 0;
  
    // Find maximum sum across all rows
    for(int i = 0; i < n; i++) {
        int sum = 0;
        for(int j = 0; j < n; j++)
            sum += mat[i][j];
        maxSum = max(sum, maxSum);
    }
  
    // Find maximum sum across all columns
    for(int j = 0; j < n; j++) {
        int sum = 0;
        for(int i = 0; i < n; i++)
            sum += mat[i][j];
        maxSum = max(sum, maxSum);
    }
    
    // Sum of operations across all rows
    for(int i = 0; i < n; i++) {
        int sum = 0;
        for(int j = 0; j < n; j++) {
			sum += mat[i][j];
        }
        res += (maxSum - sum);
    }
    return res;
}

int main() {
    vector<vector<int>> mat = {
      { 1, 2, 3 }, 
      { 4, 2, 3 }, 
      { 3, 2, 1 }
    };
    cout << findMinOperation(mat);
    return 0;
}
Java
// Java program to find minimum operation required to make sum
// of each row and column equals

import java.util.*;

class GfG {
    static int findMinOperation(int[][] mat) {
        int n = mat.length;
        int res = 0;
        int maxSum = 0;

        // Find maximum sum across all rows
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = 0; j < n; j++) {
                sum += mat[i][j];
            }
            maxSum = Math.max(sum, maxSum);
        }

        // Find maximum sum across all columns
        for (int j = 0; j < n; j++) {
            int sum = 0;
            for (int i = 0; i < n; i++) {
                sum += mat[i][j];
            }
            maxSum = Math.max(sum, maxSum);
        }

        // Sum of operations across all rows
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = 0; j < n; j++) {
                sum += mat[i][j];
            }
            res += (maxSum - sum);
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            { 1, 2, 3 },
            { 4, 2, 3 },
            { 3, 2, 1 }
        };
        System.out.println(findMinOperation(mat));
    }
}
Python
# Python program to find minimum operation required to make sum
# of each row and column equals

def findMinOperation(mat):
    n = len(mat)
    res = 0
    maxSum = 0
    
    # Find maximum sum across all rows
    for i in range(n):
        sum = 0
        for j in range(n):
            sum += mat[i][j]
        maxSum = max(sum, maxSum)
    
    # Find maximum sum across all columns
    for j in range(n):
        sum = 0
        for i in range(n):
            sum += mat[i][j]
        maxSum = max(sum, maxSum)
    
    # Sum of operations across all rows
    for i in range(n):
        sum = 0
        for j in range(n):
            sum += mat[i][j]
        res += (maxSum - sum)
    
    return res


if __name__ == "__main__":
    mat = [
      [1, 2, 3], 
      [4, 2, 3], 
      [3, 2, 1]
    ]
    print(findMinOperation(mat))
C#
// C# program to find minimum operation required to make sum
// of each row and column equals

using System;
using System.Collections.Generic;

class GfG {
    static int FindMinOperation(int[][] mat) {
        int n = mat.Length;
        int res = 0;
        int maxSum = 0;

        // Find maximum sum across all rows
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = 0; j < n; j++)
                sum += mat[i][j];
            maxSum = Math.Max(sum, maxSum);
        }

        // Find maximum sum across all columns
        for (int j = 0; j < n; j++) {
            int sum = 0;
            for (int i = 0; i < n; i++)
                sum += mat[i][j];
            maxSum = Math.Max(sum, maxSum);
        }

        // Sum of operations across all rows
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = 0; j < n; j++)
                sum += mat[i][j];
            res += (maxSum - sum);
        }
        return res;
    }

    static void Main(string[] args) {
        int[][] mat = {
            new int[] { 1, 2, 3 },
            new int[] { 4, 2, 3 },
            new int[] { 3, 2, 1 }
        };
        Console.WriteLine(FindMinOperation(mat));
    }
}
JavaScript
// JavaScript program to find minimum operation required to make sum
// of each row and column equals

function findMinOperation(mat) {
    let n = mat.length;
    let res = 0;
    let maxSum = 0;

    // Find maximum sum across all rows
    for (let i = 0; i < n; i++) {
        let sum = 0;
        for (let j = 0; j < n; j++) {
            sum += mat[i][j];
        }
        maxSum = Math.max(sum, maxSum);
    }

    // Find maximum sum across all columns
    for (let j = 0; j < n; j++) {
        let sum = 0;
        for (let i = 0; i < n; i++) {
            sum += mat[i][j];
        }
        maxSum = Math.max(sum, maxSum);
    }

    // Sum of operations across all rows
    for (let i = 0; i < n; i++) {
        let sum = 0;
        for (let j = 0; j < n; j++) {
            sum += mat[i][j];
        }
        res += (maxSum - sum);
    }
    return res;
}

// Driver Code
let mat = [
    [ 1, 2, 3 ], 
    [ 4, 2, 3 ], 
    [ 3, 2, 1 ]
];
console.log(findMinOperation(mat));

Output
6

Time complexity: O(n2), Traversing the matrix for calculating sum of each row and each column
Auxiliary space: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads