Minimum inversions required so that no two adjacent elements are same | Function to return the minimum inversions required so that no two adjacent elements are same ; To store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; Find all the changes required ; Return the required answer ; Driver code
def min_changes ( a , n ) : NEW_LINE INDENT ans_a = 0 ; NEW_LINE ans_b = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans_a += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans_b += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans_b += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans_a += 1 ; NEW_LINE DEDENT DEDENT DEDENT return min ( ans_a , ans_b ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( min_changes ( a , n ) ) ; NEW_LINE DEDENT