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)
- Maximum size square sub-matrix with all 1s
- Print a given matrix in spiral form
- Search in a row wise and column wise sorted matrix
- A Boolean Matrix Question
- Performance analysis of Row major and Column major order of storing arrays in C
- Matrix Chain Multiplication | DP-8
- Print unique rows in a given boolean matrix
- Inplace (Fixed space) M x N size matrix transpose | Updated
- Maximum sum rectangle in a 2D matrix | DP-27
- Zigzag (or diagonal) traversal of Matrix
- Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
- Print all possible paths from top left to bottom right of a mXn matrix
- Count all possible paths from top left to bottom right of a mXn matrix
- Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
- Printing brackets in Matrix Chain Multiplication Problem
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 : Ita_c