Suppose we have an array of positive numbers; we replace each element from that array array so that the difference between two adjacent elements in the array is either less than or equal to a given target. Now, we have to minimize the adjustment cost, so the sum of differences between new value and old value. More precisely, we minimize ∑|A[i] – Anew[i]| where i in range 0 to n-1, here n is denoted as size of A and Anew is the array with adjacent difference less than or equal to target.
So, if the input is like [56, 78, 53, 62, 40, 7, 26, 61, 50, 48], target = 20, then the output will be 25
To solve this, we will follow these steps −
n := size of arr
table := [[0 for i in range 0 to M + 1] for i in range 0 to n]
for j in range 0 to M + 1, do
table[0, j] := |j - arr[0]|
for i in range 1 to n, do
for j in range 0 to M + 1, do
table[i, j] := 100000000
for k in range maximum of (j-target and 0) and minimum of (M and j + target), do
table[i,j] = minimum of table[i,j], table[i - 1,k] + |arr[i] - j|
ans := 10000000
for j in range 0 to M + 1, do
ans = minimum of ans and table[n-1, j]
return ans
Example
Let us see the following implementation to get better understanding −
M = 100 def get_min_cost(arr, target): n = len(arr) table = [[0 for i in range(M + 1)] for i in range(n)] for j in range(M + 1): table[0][j] = abs(j - arr[0]) for i in range(1, n): for j in range(M + 1): table[i][j] = 100000000 for k in range(max(j - target, 0), min(M, j + target) + 1): table[i][j] = min(table[i][j], table[i - 1][k] + abs(arr[i] - j)) ans = 10000000 for j in range(M + 1): ans = min(ans, table[n - 1][j]) return ans arr= [56, 78, 53, 62, 40, 7, 26, 61, 50, 48] target = 20 print(get_min_cost(arr, target))
Input
[56, 78, 53, 62, 40, 7, 26, 61, 50, 48], 20
Output
35