Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd | C ++ program for the above approach ; Function to count reversals to separate elements with same parity ; Traverse the given array ; Count size of subarray having integers with same parity only ; Otherwise ; Reversals required is equal to one less than subarray size ; Return the total reversals ; Function to print the array elements ; Function to count the minimum reversals required to make make sum of all adjacent elements odd ; Stores operations required for separating adjacent odd elements ; Stores operations required for separating adjacent even elements ; Maximum of two is the return ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int separate ( int arr [ ] , int n , int parity ) { int count = 1 , res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( ( arr [ i ] + parity ) & 1 ) && ( ( arr [ i - 1 ] + parity ) & 1 ) ) count ++ ; else { if ( count > 1 ) res += count - 1 ; count = 1 ; } } return res ; } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void requiredOps ( int arr [ ] , int N ) { int res1 = separate ( arr , N , 0 ) ; int res2 = separate ( arr , N , 1 ) ; cout << max ( res1 , res2 ) ; } int main ( ) { int arr [ ] = { 13 , 2 , 6 , 8 , 3 , 5 , 7 , 10 , 14 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; requiredOps ( arr , N ) ; return 0 ; }