Maximum sum of elements from each row in the matrix | PHP Program to find row - wise maximum element sum considering elements in increasing order . ; Function to perform given task ; Getting the maximum element from last row ; Comparing it with the elements of above rows ; Maximum of current row . ; If we could not an element smaller than prev_max . ; Driver code
< ? php $ N = 3 ; function getGreatestSum ( $ a ) { global $ N ; $ prev_max = 0 ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) if ( $ prev_max < $ a [ $ N - 1 ] [ $ j ] ) $ prev_max = $ a [ $ N - 1 ] [ $ j ] ; $ sum = $ prev_max ; for ( $ i = $ N - 2 ; $ i >= 0 ; $ i -- ) { $ curr_max = PHP_INT_MIN ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) if ( $ prev_max > $ a [ $ i ] [ $ j ] and $ a [ $ i ] [ $ j ] > $ curr_max ) $ curr_max = $ a [ $ i ] [ $ j ] ; if ( $ curr_max == PHP_INT_MIN ) return -1 ; $ prev_max = $ curr_max ; $ sum += $ prev_max ; } return $ sum ; } $ a = array ( array ( 1 , 2 , 3 ) , array ( 4 , 5 , 6 ) , array ( 7 , 8 , 9 ) ) ; echo getGreatestSum ( $ a ) , " STRNEWLINE " ; $ b = array ( array ( 4 , 5 , 6 ) , array ( 4 , 5 , 6 ) , array ( 4 , 5 , 6 ) ) ; echo getGreatestSum ( $ b ) , " STRNEWLINE " ; ? >