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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum operations required to set all elements of binary matrix
- Minimum number of operations required to set all elements of a binary matrix
- Minimum changes required to make each path in a matrix palindrome
- 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
- Minimum steps required to reach the end of a matrix | Set 2
- Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
- Find minimum steps required to reach the end of a matrix | Set - 1
- Find minimum steps required to reach the end of a matrix | Set 2
- 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
- Check if a given matrix can be converted to another given matrix by row and column exchanges
- 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
- Maximum size square Sub-Matrix with sum less than or equals to K
- Sum of middle row and column in Matrix
- Print an N x M matrix such that each row and column has all the vowels in it
- Find column with maximum sum in a Matrix
Improved By : chitranayal