Lowest cost to adjust integer array, adjacencies differ less than k

By | January 2, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

This problem frustrates me for a long time. Yesterday, I finally comprehended. Cheers!

Problem: Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a given number k. If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|.

Solution: Find the max and min in A. So we know each of element, it is obvious to know that their change should be within [min, max]. So let’s say see A[0]. We change it to every number between [min, max], and record the cost.
Go to A[1]. We change A[1] to every number between [min,max]. It has a cost by itself. Besides, we should consider the cost from A[0]. Let’s say A[1] want to change to a certain number B[1]=bi, and b1 is between [min,max]. So, before b1, the A[0] could range from [b1-k,b1+k]. We want to choose the minimum cost. So the minimum cost of bi equals min{cost of A[0] changing to bi-k, cost of A[0] changing to bi-k+1,…,cost of A[0] changing to bi,…,cost of A[0] changing to bi+k} + (cost of A[1] changing to bi).
Then, we iterate A[2], A[3] and so on.
It requires a matrix to store it. Let’s say it is DP[max-min][A.length].
DP[i][j] means the minimum cost of changing A[0,…,j] to the target series when we changee A[j] to i.

Take the following as example, it is from careercup link:
On each number from the first to last, calculate the total cost up to this number with the ending number. Thus we calculate a matrix with column as the order of the number, row as ending number, cell value as a pair of total cost so far and row number of previous column to reach this cell(for path). The cell with the lowest cost in the last column is the result. From that cell, we can get the cell on each column to reach this last cell. The row and column indices for cells on the path make the result sequences.
For example:
input : 1, 4, 2, 3
matrix:
1 2 3 4
1 (0, -1) (3, 1) (4, 1) (6, 1)
2 (1, -1) (2, 1) (2, 2) (3, 2)
3 (2, -1) (2, 2) (3, 2) (2, 2)
4 (3, -1) (2, 3) (4, 3) (4, 3)
So the last cell[3,4] has lowest cost of 2, the previous cell is [2,3] with cost 2, then previous is [2,2] with cost 2 and then [1,1]. The result sequence is ( 1, 2, 2, 3) . This result has the same cost as the sequence of (2,3,2,3).