![]() |
VOOZH | about |
Given a square matrix mat[][], Find the minimum number of operations required to make the sum of elements in each row and each column equal. In one operation, you are allowed to increment any individual cell 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.
Table of Content
The naive approach incrementally adjusts the matrix by always increasing the element at the intersection of the row and column with the minimum sums. This is repeated until all row and column sums become equal. It simulates the process step-by-step without optimization, leading to high time complexity.
Why it works:
6
Time Complexity: O(n2 * maxEleDiff) where maxEleDiff is the difference between the maximum and minimum sum values.
Auxiliary Space: O(n) for row and column sum arrays.
The idea is to equalize all row and column sums, so for that we will first compute: maxSum = max(maxRowSum, maxColSum).
We aim to make every row and column sum equal to maxSum. To do this, we increment elements only in rows and columns that fall short of maxSum, ensuring we never exceed maxSum for any row or column. Each increment at a cell (i, j) contributes to both the row and column sums.
Why this approach works
At this point:
Thus, all rows and columns are exactly maxSum, and we've used the minimum number of operations:
minOperations = n × s – totalSum
6