Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum difference of sum of elements in two rows in a matrix in C
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.
Syntax
int rowmaxd(int M[][MAX], int row, int col);
Approach
- Calculate the sum of elements for each row of the matrix
- Store these row sums in an array
- Find the maximum difference between any two row sums where the larger sum comes from a row with higher index
- Use the concept of finding maximum difference in an array where j > i
Example
#include <stdio.h>
#define MAX 100
// Function to calculate maximum difference between sum of elements of two rows
int rowmaxd(int M[][MAX], int row, int col) {
// Array for storing sum of elements of each row
int RSum[row];
// Calculate sum of each 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 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 (int i = 1; i < row; i++) {
// If this difference is more than MD, then 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;
}
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}};
printf("Maximum difference of sum of elements in two rows in a matrix is: %d<br>", rowmaxd(mat, r, c));
return 0;
}
Output
Maximum difference of sum of elements in two rows in a matrix is: 5
How It Works
The algorithm works by:
- Step 1: Computing row sums: [8, 10, 11, 13, 4]
- Step 2: Finding maximum difference where later row sum minus earlier row sum gives maximum value
- Step 3: Tracking minimum seen so far and maximum difference simultaneously
Conclusion
This approach efficiently finds the maximum difference between row sums in O(n*m) time complexity where n is rows and m is columns. It uses the principle of finding maximum difference in an array with positional constraints.
