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
function minimumCost ( arr , cost , N ) { var dp = Array ( N ) . fill ( ) . map ( ( ) => Array ( 3 ) . fill ( 0 ) ) ; dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = cost [ 0 ] ; dp [ 0 ] [ 2 ] = cost [ 0 ] * 2 ; for ( i = 1 ; i < N ; i ++ ) { for ( j = 0 ; j < 3 ; j ++ ) { var minimum = parseInt ( 1e6 ) ; if ( j + arr [ i ] != arr [ i - 1 ] ) minimum = Math . min ( minimum , dp [ i - 1 ] [ 0 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 1 ) minimum = Math . min ( minimum , dp [ i - 1 ] [ 1 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 2 ) minimum = Math . min ( minimum , dp [ i - 1 ] [ 2 ] ) ; dp [ i ] [ j ] = j * cost [ i ] + minimum ; } } var ans = parseInt ( 1e6 ) ; for ( i = 0 ; i < 3 ; i ++ ) ans = Math . min ( ans , dp [ N - 1 ] [ i ] ) ; document . write ( ans + " " ) ; } var arr = [ 1 , 1 , 2 , 2 , 3 , 4 ] ; var cost = [ 3 , 2 , 5 , 4 , 2 , 1 ] ; var N = arr . length ; minimumCost ( arr , cost , N ) ;