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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int arr [ ] , int cost [ ] , int N ) { vector < vector < int > > dp ( N , vector < int > ( 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 = 1e6 ; if ( j + arr [ i ] != arr [ i - 1 ] ) minimum = min ( minimum , dp [ i - 1 ] [ 0 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 1 ) minimum = min ( minimum , dp [ i - 1 ] [ 1 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 2 ) minimum = min ( minimum , dp [ i - 1 ] [ 2 ] ) ; dp [ i ] [ j ] = j * cost [ i ] + minimum ; } } int ans = 1e6 ; for ( int i = 0 ; i < 3 ; i ++ ) ans = min ( ans , dp [ N - 1 ] [ i ] ) ; cout << ans << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 , 4 } ; int cost [ ] = { 3 , 2 , 5 , 4 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumCost ( arr , cost , N ) ; return 0 ; }