Maximum difference of sum of elements in two rows in a matrix | C ++ program to find maximum difference of sum of elements of two rows ; Function to find maximum difference of sum of elements of two rows such that second row appears before first row . ; auxiliary array to store sum of all elements of each row ; calculate sum of each row and store it in rowSum array ; calculating maximum difference of two elements such that rowSum [ i ] < rowsum [ j ] ; if current difference is greater than previous then update it ; if new element is less than previous minimum element then update it so that we may get maximum difference in remaining array ; Driver program to run the case
#include <bits/stdc++.h> NEW_LINE #define MAX  100 NEW_LINE using namespace std ; int maxRowDiff ( int mat [ ] [ MAX ] , int m , int n ) { int rowSum [ m ] ; for ( int i = 0 ; i < m ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) sum += mat [ i ] [ j ] ; rowSum [ i ] = sum ; } int max_diff = rowSum [ 1 ] - rowSum [ 0 ] ; int min_element = rowSum [ 0 ] ; for ( int i = 1 ; i < m ; i ++ ) { if ( rowSum [ i ] - min_element > max_diff ) max_diff = rowSum [ i ] - min_element ; if ( rowSum [ i ] < min_element ) min_element = rowSum [ i ] ; } return max_diff ; } int main ( ) { int m = 5 , n = 4 ; int mat [ ] [ MAX ] = { { -1 , 2 , 3 , 4 } , { 5 , 3 , -2 , 1 } , { 6 , 7 , 2 , -3 } , { 2 , 9 , 1 , 4 } , { 2 , 1 , -2 , 0 } } ; cout << maxRowDiff ( mat , m , n ) ; return 0 ; }