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
def parity ( a ) : NEW_LINE INDENT return a % 3 NEW_LINE DEDENT def solve ( array , size ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( 0 , size - 1 ) : NEW_LINE INDENT if parity ( array [ i ] ) == parity ( array [ i + 1 ] ) : NEW_LINE INDENT operations += 1 NEW_LINE if i + 2 < size : NEW_LINE INDENT pari1 = parity ( array [ i ] ) NEW_LINE pari2 = parity ( array [ i + 2 ] ) NEW_LINE if pari1 == pari2 : NEW_LINE INDENT if pari1 == 0 : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT elif pari1 == 1 : NEW_LINE INDENT array [ i + 1 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( ( pari1 == 0 and pari2 == 1 ) or ( pari1 == 1 and pari2 == 0 ) ) : NEW_LINE INDENT array [ i + 1 ] = 2 NEW_LINE DEDENT if ( ( pari1 == 1 and pari2 == 2 ) or ( pari1 == 2 and pari2 == 1 ) ) : NEW_LINE INDENT array [ i + 1 ] = 0 NEW_LINE DEDENT if ( ( pari1 == 2 and pari2 == 0 ) and ( pari1 == 0 and pari2 == 2 ) ) : NEW_LINE INDENT array [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return operations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT array = [ 2 , 1 , 3 , 0 ] NEW_LINE size = len ( array ) NEW_LINE print ( solve ( array , size ) ) NEW_LINE DEDENT