Maximum value obtained by performing given operations in an Array | C ++ implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMax ( int a [ ] , int n ) { int dp [ n ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = a [ 0 ] + a [ 1 ] ; dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 1 ] ; for ( int i = 1 ; i <= n - 2 ; i ++ ) { dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i + 1 ] ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] - a [ i ] + a [ i ] * a [ i + 1 ] ; } cout << max ( dp [ n - 2 ] [ 0 ] , dp [ n - 2 ] [ 1 ] ) ; } int main ( ) { int arr [ ] = { 5 , -1 , -5 , -3 , 2 , 9 , -4 } ; findMax ( arr , 7 ) ; }