Maximize difference between sum of even and odd | C ++ program to implement the above approach ; Function to find the maximum possible difference between sum of even and odd indices ; Convert arr [ ] into 1 - based indexing ; Reverse the array ; Convert arr [ ] into 1 based index ; Reverse the array ; Stores maximum difference between sum of even and odd indexed elements ; Traverse the array ; If arr [ i ] is local maxima ; Update maxDiff ; If arr [ i ] is local minima ; Update maxDiff ; Driver Code ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPossibleDiff ( vector < int > & arr , int N ) { arr . push_back ( -1 ) ; reverse ( arr . begin ( ) , arr . end ( ) ) ; arr . push_back ( -1 ) ; reverse ( arr . begin ( ) , arr . end ( ) ) ; int maxDiff = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] && arr [ i ] > arr [ i + 1 ] ) { maxDiff += arr [ i ] ; } if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] < arr [ i + 1 ] ) { maxDiff -= arr [ i ] ; } } cout << maxDiff ; } int main ( ) { vector < int > arr = { 3 , 2 , 1 , 4 , 5 , 2 , 1 , 7 , 8 , 9 } ; int N = arr . size ( ) ; maxPossibleDiff ( arr , N ) ; return 0 ; }