Maximum sum of elements from each row in the matrix | Java 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 Program to test above function
class GFG { static final int N = 3 ; static int getGreatestSum ( int a [ ] [ ] ) { int prev_max = 0 ; for ( int j = 0 ; j < N ; j ++ ) if ( prev_max < a [ N - 1 ] [ j ] ) prev_max = a [ N - 1 ] [ j ] ; int sum = prev_max ; for ( int i = N - 2 ; i >= 0 ; i -- ) { int curr_max = - 2147483648 ; for ( int 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 ; } public static void main ( String arg [ ] ) { int a [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; System . out . println ( getGreatestSum ( a ) ) ; int b [ ] [ ] = { { 4 , 5 , 6 } , { 4 , 5 , 6 } , { 4 , 5 , 6 } } ; System . out . println ( getGreatestSum ( b ) ) ; } }