Given two integer arrays arr[] and cost[] of size** N**, the task is to make all adjacent elements distinct at minimum cost. cost[i] denotes the cost to increment ith element by 1.


Input:_ arr[] = {2, 2, 3}, cost[] = {4, 1, 5}_

Output:_ 2_


The second element has minimum increment cost. Hence, increase the cost of the second element twice.

Therefore the resultant array: {2, 4, 3}

Input:_ arr[] = {1, 2, 3}, cost[] = {7, 8, 3}_

Output:_ 0_

Recommended: Please try your approach on {IDE} first, before moving on to the solution.


  • We can observe that there an element might need to be increased maximum twice.
  • This problem can be solved using Dynamic Programming.
  • Create a DP-table dp[][], where rows represent the elements, and columns represent the increment.
  • dp[i][j] is the minimum cost required to make ith element distinct from its adjacent elements using j increments.
  • The value of dp[i][j] can be calculated as:

dp[i][j] = j * cost[i] + (minimum from previous element if both elements are different)

#arrays #dynamic programming #greedy

Minimize the cost to make all the adjacent elements distinct in an Array
12.90 GEEK