text: Minimize the count of adjacent pairs with different parity | Javascript implementation of above approach ; Recursive function to calculate minimum adjacent pairs with different parity ; If all the numbers are placed ; If replacement is not required ; If replacement is required ; backtracking ; backtracking ; Function to display the minimum number of adjacent elements with different parity ; Store no of even numbers not present in the array ; Store no of odd numbers not present in the array ; Erase exisiting numbers ; Store non - exisiting even and odd numbers ; Driver code
code: var min = 10000 ; function parity ( even , odd , v , i ) { if ( i == v . length even . length == 0 && odd . length == 0 ) { var count = 0 ; for ( var j = 0 ; j < v . length - 1 ; j ++ ) { if ( v [ j ] % 2 != v [ j + 1 ] % 2 ) count ++ ; } if ( count < min ) min = count ; return min ; } if ( v [ i ] != - 1 ) min = parity ( even , odd , v , i + 1 ) ; else { if ( even . length != 0 ) { var x = even . back ( ) ; even . pop ( ) ; v [ i ] = x ; min = parity ( even , odd , v , i + 1 ) ; even . push ( x ) ; } if ( odd . length != 0 ) { var x = odd [ odd . length - 1 ] ; odd . pop ( ) ; v [ i ] = x ; min = parity ( even , odd , v , i + 1 ) ; odd . push ( x ) ; } } return min ; } function minDiffParity ( v , n ) { var even = [ ] ; var odd = [ ] ; var m = new Map ( ) ; for ( var i = 1 ; i <= n ; i ++ ) m . set ( i , 1 ) ; for ( var i = 0 ; i < v . length ; i ++ ) { if ( v [ i ] != - 1 ) m . delete ( v [ i ] ) ; } m . forEach ( ( value , key ) => { if ( i . first % 2 == 0 ) even . push ( key ) ; else odd . push ( key ) ; } ) ; min = parity ( even , odd , v , 0 ) ; document . write ( min ) ; } var n = 8 ; var v = [ 2 , 1 , 4 , - 1 , - 1 , 6 , - 1 , 8 ] ; minDiffParity ( v , n ) ;