Maximum difference of sum of elements in two rows in a matrix | 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 code
function maxRowDiff ( mat , m , n ) { let rowSum = new Array ( m ) ; for ( let i = 0 ; i < m ; i ++ ) { let sum = 0 ; for ( let j = 0 ; j < n ; j ++ ) sum += mat [ i ] [ j ] ; rowSum [ i ] = sum ; } let max_diff = rowSum [ 1 ] - rowSum [ 0 ] ; let min_element = rowSum [ 0 ] ; for ( let 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 ; } let m = 5 , n = 4 ; let mat = [ [ - 1 , 2 , 3 , 4 ] , [ 5 , 3 , - 2 , 1 ] , [ 6 , 7 , 2 , - 3 ] , [ 2 , 9 , 1 , 4 ] , [ 2 , 1 , - 2 , 0 ] ] ; document . write ( maxRowDiff ( mat , m , n ) ) ;