For all the possible sizes of the jth group that end at the ith element we pick the size that gives us the minimum cost for dp ( i , j ) elementsToChange is the cost of making all the elements in the jth group identical and we make use of dp ( it - 1 , j - 1 ) to find the overall minimal cost
dp [ i ] [ j ] = min ( dp [ it - 1 ] [ j - 1 ] + elementsToChange , dp [ i ] [ j ] ) ; } } } }