Given a square matrix of size . Find minimum number of operation are required such that sum of elements on each row and column becomes equals. In one operation, increment any value of cell of matrix by 1. In first line print minimum operation required and in next ‘n’ lines print ‘n’ integers representing the final matrix after operation.
Input: 1 2 3 4 Output: 4 4 3 3 4 Explanation 1. Increment value of cell(0, 0) by 3 2. Increment value of cell(0, 1) by 1 Hence total 4 operation are required Input: 9 1 2 3 4 2 3 3 2 1 Output: 6 2 4 3 4 2 3 3 3 3
The approach is simple, 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 operation needed to make the sum on row ‘i’ equals to maxSum and Yj is the total number of operation needed to make the sum on column ‘j’ equals to maxSum. Since Xi = Yj so we need to work at any one of them according to the condition.
In order to minimise 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 increment.
Below is the implementation of the above approach.
Output 4 4 3 3 4
Time complexity: O(n2)
Auxiliary space: O(n)
- Minimum operations required to set all elements of binary matrix
- Minimum flip required to make Binary Matrix symmetric
- Minimum operations of given type to make all elements of a matrix equal
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Minimum element of each row and each column in a matrix
- Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
- Minimum steps required to reach the end of a matrix | Set 2
- Find minimum steps required to reach the end of a matrix | Set 2
- Find minimum steps required to reach the end of a matrix | Set - 1
- Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
- Minimum changes needed to make a 3*3 matrix magic square
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Check if it is possible to make the given matrix increasing matrix or not
- Sum of middle row and column in Matrix
- Program to find the Sum of each Row and each Column of a Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : chitranayal