Minimum operations required to modify the array such that parity of adjacent elements is different | Function to return the parity of a number ; Function to return the minimum number of operations required ; Operation needs to be performed ; Parity of previous element ; Parity of next element ; Update parity of current element to be other than the parities of the previous and the next number ; Driver Code
< ? php function parity ( $ a ) { return $ a % 3 ; } function solve ( $ array , $ size ) { $ operations = 0 ; for ( $ i = 0 ; $ i < $ size - 1 ; $ i ++ ) { if ( parity ( $ array [ $ i ] ) == parity ( $ array [ $ i + 1 ] ) ) { $ operations ++ ; if ( $ i + 2 < $ size ) { $ pari1 = parity ( $ array [ $ i ] ) ; $ pari2 = parity ( $ array [ $ i + 2 ] ) ; if ( $ pari1 == $ pari2 ) { if ( $ pari1 == 0 ) $ array [ $ i + 1 ] = 1 ; else if ( $ pari1 == 1 ) $ array [ $ i + 1 ] = 0 ; else $ array [ $ i + 1 ] = 1 ; } else { if ( ( $ pari1 == 0 && $ pari2 == 1 ) || ( $ pari1 == 1 && $ pari2 == 0 ) ) $ array [ $ i + 1 ] = 2 ; if ( ( $ pari1 == 1 && $ pari2 == 2 ) || ( $ pari1 == 2 && $ pari2 == 1 ) ) $ array [ $ i + 1 ] = 0 ; if ( ( $ pari1 == 2 && $ pari2 == 0 ) || ( $ pari1 == 0 && $ pari2 == 2 ) ) $ array [ $ i + 1 ] = 1 ; } } } } return $ operations ; } $ array = array ( 2 , 1 , 3 , 0 ) ; $ size = count ( $ array ) ; echo solve ( $ array , $ size ) ; ? >