text: Maximum sum possible from given Matrix by performing given operations | C ++ program for the above approach ; Function to print the maximum sum ; Dp table ; Initializing dp array with 0 s ; Base case ; Traverse each column ; Update answer for both rows ; Print the maximum sum ; Driver Code ; Given array ; Number of Columns ; Function calls
code: #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void maxSum ( vector < vector < int > > arr , int n , int m ) { vector < vector < int > > dp ( n ) ; for ( int i = 0 ; i < 2 ; i ++ ) { dp [ i ] = vector < int > ( m ) ; for ( int j = 0 ; j < m ; j ++ ) { dp [ i ] [ j ] = 0 ; } } dp [ 0 ] [ m - 1 ] = arr [ 0 ] [ m - 1 ] ; dp [ 1 ] [ m - 1 ] = arr [ 1 ] [ m - 1 ] ; for ( int j = m - 2 ; j >= 0 ; j -- ) { for ( int i = 0 ; i < 2 ; i ++ ) { if ( i == 1 ) { dp [ i ] [ j ] = max ( arr [ i ] [ j ] + dp [ 0 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 0 ] [ j + 2 ] ) ; } else { dp [ i ] [ j ] = max ( arr [ i ] [ j ] + dp [ 1 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 1 ] [ j + 2 ] ) ; } } } cout << max ( dp [ 0 ] [ 0 ] , dp [ 1 ] [ 0 ] ) ; } int main ( ) { vector < vector < int > > arr = { { 1 , 50 , 21 , 5 } , { 2 , 10 , 10 , 5 } } ; int N = arr [ 0 ] . size ( ) ; maxSum ( arr , 2 , N ) ; return 0 ; }