Maximum sum of elements from each row in the matrix | JavaScript Program to find row - wise maximum element sum considering elements in increasing orderers ; 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
let N = 3 ; function getGreatestSum ( a ) { let prev_max = 0 ; for ( let j = 0 ; j < N ; j ++ ) if ( prev_max < a [ N - 1 ] [ j ] ) prev_max = a [ N - 1 ] [ j ] ; let sum = prev_max ; for ( let i = N - 2 ; i >= 0 ; i -- ) { let curr_max = - 2147483648 ; for ( let j = 0 ; j < N ; j ++ ) if ( prev_max > a [ i ] [ j ] && a [ i ] [ j ] > curr_max ) curr_max = a [ i ] [ j ] ; if ( curr_max == - 2147483648 ) return - 1 ; prev_max = curr_max ; sum += prev_max ; } return sum ; } let a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; document . write ( getGreatestSum ( a ) + " " ) ; let b = [ [ 4 , 5 , 6 ] , [ 4 , 5 , 6 ] , [ 4 , 5 , 6 ] ] ; document . write ( getGreatestSum ( b ) ) ;