Maximum difference of sum of elements in two rows in a matrix | PHP 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 Code
< ? php $ MAX = 100 ; function maxRowDiff ( $ mat , $ m , $ n ) { global $ MAX ; $ rowSum = array ( ) ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) { $ sum = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) $ sum += $ mat [ $ i ] [ $ j ] ; $ rowSum [ $ i ] = $ sum ; } $ max_diff = $ rowSum [ 1 ] - $ rowSum [ 0 ] ; $ min_element = $ rowSum [ 0 ] ; for ( $ 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 ; } $ m = 5 ; $ n = 4 ; $ mat = array ( array ( -1 , 2 , 3 , 4 ) , array ( 5 , 3 , -2 , 1 ) , array ( 6 , 7 , 2 , -3 ) , array ( 2 , 9 , 1 , 4 ) , array ( 2 , 1 , -2 , 0 ) ) ; echo maxRowDiff ( $ mat , $ m , $ n ) ; ? >