Maximize count of odd | C ++ code implementation for above approach ; To find maximum number of pairs in array with conversion of at most one element ; Initialize count of even elements ; Initialize count of odd elements ; If current number is even then increment x by 1 ; If current number is odd then increment y by 1 ; Initialize the answer by min ( x , y ) ; If difference in count of odd and even is more than 2 than increment answer ; Return final answer ; Driver code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumNumberofpairs ( int n , int arr [ ] ) { int x = 0 ; int y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { x ++ ; } else { y ++ ; } } int answer = min ( x , y ) ; if ( abs ( x - y ) >= 2 ) { answer ++ ; } return answer ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 6 , 5 , 10 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumNumberofpairs ( n , arr ) << endl ; return 0 ; }