Minimize the cost to make all the adjacent elements distinct in an Array | Function that prints minimum cost required ; Dp - table ; Base case Not increasing the first element ; Increasing the first element by 1 ; Increasing the first element by 2 ; Condition if current element is not equal to previous non - increased element ; Condition if current element is not equal to previous element after being increased by 1 ; Condition if current element is not equal to previous element after being increased by 2 ; Take the minimum from all cases ; Finding the minimum cost ; Printing the minimum cost required to make all adjacent elements distinct ; Driver Code
def minimumCost ( arr , cost , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 3 ) ] for i in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE dp [ 0 ] [ 1 ] = cost [ 0 ] NEW_LINE dp [ 0 ] [ 2 ] = cost [ 0 ] * 2 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT minimum = 1e6 NEW_LINE if ( j + arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT if ( j + arr [ i ] != arr [ i - 1 ] + 1 ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT if ( j + arr [ i ] != arr [ i - 1 ] + 2 ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 2 ] ) NEW_LINE DEDENT dp [ i ] [ j ] = j * cost [ i ] + minimum NEW_LINE DEDENT DEDENT ans = 1e6 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT ans = min ( ans , dp [ N - 1 ] [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 3 , 4 ] NEW_LINE cost = [ 3 , 2 , 5 , 4 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE minimumCost ( arr , cost , N ) NEW_LINE DEDENT