Reverse a subarray of the given array to minimize the sum of elements at even position | C ++ implementation to reverse a subarray of the given array to minimize the sum of elements at even position ; Function that will give the max negative value ; Check for count greater than 0 as we require only negative solution ; Function to print the minimum sum ; Taking sum of only even index elements ; Initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; Get the max negative value ; Driver code
#include <bits/stdc++.h> NEW_LINE #define N  5 NEW_LINE using namespace std ; int after_rev ( vector < int > v ) { int mini = 0 , count = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { count += v [ i ] ; if ( count > 0 ) count = 0 ; if ( mini > count ) mini = count ; } return mini ; } void print ( int arr [ N ] ) { int sum = 0 ; for ( int i = 0 ; i < N ; i += 2 ) sum += arr [ i ] ; vector < int > v1 , v2 ; for ( int i = 0 ; i + 1 < N ; i += 2 ) v1 . push_back ( arr [ i + 1 ] - arr [ i ] ) ; for ( int i = 1 ; i + 1 < N ; i += 2 ) v2 . push_back ( arr [ i ] - arr [ i + 1 ] ) ; int change = min ( after_rev ( v1 ) , after_rev ( v2 ) ) ; if ( change < 0 ) sum += change ; cout << sum << endl ; } int main ( ) { int arr [ N ] = { 0 , 1 , 4 , 3 } ; print ( arr ) ; return 0 ; }