- Related Questions & Answers
- Find minimum adjustment cost of an array in C++
- Connecting Cities With Minimum Cost in Python
- Program to find minimum total cost for equalizing list elements in Python
- Program to Find Out the Minimum Cost to Purchase All in Python
- Find minimum cost to buy all books in C++
- Minimum Cost Tree From Leaf Values in Python
- Minimum Cost Polygon Triangulation
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Find indexes of multiple minimum value in an array in JavaScript
- Program to find to get minimum cost to climb at the top of stairs in Python?
- How to find the minimum value of an array in JavaScript?
- Python - Window size Adjustment in Kivy
- Program to find minimum cost to reduce a list into one integer in Python
- Program to find minimum cost to paint fences with k different colors in Python
- Minimum Cost For Tickets in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[56, 78, 53, 62, 40, 7, 26, 61, 50, 48], 20

35

Advertisements