We are given a matrix and the task is to find the greatest difference between the sum of elements in two rows of a matrix. Suppose we have a matrix M[i,j] with i rows and j columns. Let the rows be R0 to Ri-1. The difference will be calculated by subtracting the (sum of elements of Ry) - (sum of elements of Rx), where x<y.
Let’s now understand what we have to do using an example −
Input
M[4][4] = { { 1,2,0,5 }, {0,1,1,0}, {7,2,3,2} {1,2,4,1}};
Output
Maximum difference here is : 12
Explanation − Here sum of elements of Row 2 is maximum that is 14 and sum of elements of Row 1 is minimum, that is 2. So the maximum difference is 14-2=12.
Input
M[4][4] = { { 0,2,0,5 }, {0,1,4,0}, {1,2,3,2} {2,2,6,0}};
Output
Maximum difference here is : 5
Explanation − Here sum of elements of Row 4 is maximum that is 10 and sum of elements of Row 2 is minimum, that is 5. So the maximum difference is 10-5=10
Approach used in the below program as follows
Take inputs for the number of rows and columns in a matrix such that it has at-least two rows.
In the rowmaxd() function we are passing the input matrix and it’s row count and column count and returning the maximum difference of sum of rows.
Here we will first store the sum of elements of each row of matrix M[row][col] in an array named RSum[i]. Note that RSum[row] has length according to number of rows in M[row][col].
Then we will assume MD as the maximum difference between RSum[1]-RSum[0]. Here RSum[0] is the sum of all elements of row 0 and RSums[1] is the sum of all elements of row 1.
Also we are assuming that RSum[0] is least in RSum[row] and storing it in MIN variable.
In for loop from 0 to i we will traverse each RSum[row] and compare the difference between RSum[i]-MIN>MD. If it is so, update MD. Else check is RSum[row]<MIN and update MIN separately.
Example
#include<stdio.h> #define MAX 100 //create function to calculate maximum difference between sum of elements of two rows such that second row appears before the first int rowmaxd(int M[][MAX], int row, int col){ //for storing sum of elements of each row int RSum[row]; for(int i=0;i<row;i++){ int sum=0; for(int j=0;j<col;j++) sum+=M[i][j]; RSum[i]=sum; } //calculate now max difference between two elements of RSum such that in RSum[j]-RSum[i], i<j int MD=RSum[1]-RSum[0]; int MIN=RSum[0]; for (i = 1; i < row; i++){ //if this difference is more than MD,the update MD if(RSum[i]-MIN>MD) MD=RSum[i]-MIN; //if this value is even less than MIN,then update MIN if(RSum[i]<MIN) MIN=RSum[i]; } return MD; } // Driver program int main(){ int r = 5, c = 4; int mat[][MAX] = { {-1, 2, 3, 4}, {6, 3, 0, 1}, {-1, 7, 8, -3}, {3, 5, 1, 4}, {2, 1, 1, 0}}; cout<<”Maximum difference of sum of elements in two rows in a matrix is: ”<<rowmaxd(mat, r, c); return 0; }
Output
If we run the above code we will get the following output −
Maximum difference of sum of elements in two rows in a matrix: 5