Minimize the cost to make all the adjacent elements distinct in an Array | C # program to find the minimum cost required to make all adjacent elements distinct ; 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
using System ; class GFG { static void minimumCost ( int [ ] arr , int [ ] cost , int N ) { int [ , ] dp = new int [ N , 3 ] ; dp [ 0 , 0 ] = 0 ; dp [ 0 , 1 ] = cost [ 0 ] ; dp [ 0 , 2 ] = cost [ 0 ] * 2 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { int minimum = ( int ) 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 ; } } int ans = ( int ) 1e6 ; for ( int i = 0 ; i < 3 ; i ++ ) ans = Math . Min ( ans , dp [ N - 1 , i ] ) ; Console . Write ( ans + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 2 , 2 , 3 , 4 } ; int [ ] cost = { 3 , 2 , 5 , 4 , 2 , 1 } ; int N = arr . Length ; minimumCost ( arr , cost , N ) ; } }