Given an array of positive integers, replace each element in the array such that the difference between adjacent elements in the array is less than or equal to a given target. We need to minimize the adjustment cost, that is the sum of differences between new and old values. We basically need to minimize ?|A[i] – Anew[i]| where 0 ? i ? n-1, n is size of A[] and Anew[] is the array with adjacent difference less than or equal to the target. Assume all elements of the array is less than constant M = 100.
Examples:
Input: arr = [1, 3, 0, 3], target = 1
Output: Minimum adjustment cost is 3
Explanation: One of the possible solutions
is [2, 3, 2, 3]
Input: arr = [2, 3, 2, 3], target = 1
Output: Minimum adjustment cost is 0
Explanation: All adjacent elements in the input
array are already less than equal to given target
Input: arr = [55, 77, 52, 61, 39, 6,
25, 60, 49, 47], target = 10
Output: Minimum adjustment cost is 75
Explanation: One of the possible solutions is
[55, 62, 52, 49, 39, 29, 30, 40, 49, 47]
In order to minimize the adjustment cost ?|A[i] – Anew[i]| for all index i in the array, |A[i] – Anew[i]| should be as close to zero as possible. Also, |A[i] – Anew[i+1] ]| ? Target.
This problem can be solved by dynamic programming.
Let dp[i][j] defines minimal adjustment cost on changing A[i] to j, then the DP relation is defined by –
dp[i][j] = min{dp[i - 1][k]} + |j - A[i]|
for all k's such that |k - j| ? target
Here, 0 ? i ? n and 0 ? j ? M where n is the number of elements in the array and M = 100. We have to consider all k such that max(j – target, 0) ? k ? min(M, j + target)
Finally, the minimum adjustment cost of the array will be min{dp[n – 1][j]} for all 0 ? j ? M.
Algorithm:
- Create a 2D array with the initializations dp[n][M+1] to record the least adjustment cost of changing A[i] to j, where n is the array’s length and M is its maximum value.
- Calculate the smallest adjustment cost of changing A[0] to j for the first element of the array, dp[0][j], using the formula dp[0][j] = abs (j – A[0]).
- Replace A[i] with j in the remaining array elements, dp[i][j], and use the formula dp[i][j] = min(dp[i-1][k] + abs(A[i] – j)), where k takes all feasible values between max(j-target,0) and min(M,j+target), to get the minimal adjustment cost.
- As the minimum adjustment cost, give the lowest number from the last row of the dp table.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
#define M 100
int minAdjustmentCost( int A[], int n, int target)
{
int dp[n][M + 1];
for ( int j = 0; j <= M; j++)
dp[0][j] = abs (j - A[0]);
for ( int i = 1; i < n; i++)
{
for ( int j = 0; j <= M; j++)
{
dp[i][j] = INT_MAX;
for ( int k = max(j-target,0); k <= min(M,j+target); k++)
dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs (A[i] - j));
}
}
int res = INT_MAX;
for ( int j = 0; j <= M; j++)
res = min(res, dp[n - 1][j]);
return res;
}
int main()
{
int arr[] = {55, 77, 52, 61, 39, 6, 25, 60, 49, 47};
int n = sizeof (arr) / sizeof (arr[0]);
int target = 10;
cout << "Minimum adjustment cost is "
<< minAdjustmentCost(arr, n, target) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int M = 100 ;
static int minAdjustmentCost( int A[], int n, int target)
{
int [][] dp = new int [n][M + 1 ];
for ( int j = 0 ; j <= M; j++)
dp[ 0 ][j] = Math.abs(j - A[ 0 ]);
for ( int i = 1 ; i < n; i++)
{
for ( int j = 0 ; j <= M; j++)
{
dp[i][j] = Integer.MAX_VALUE;
int k = Math.max(j-target, 0 );
for ( ; k <= Math.min(M,j+target); k++)
dp[i][j] = Math.min(dp[i][j], dp[i - 1 ][k] +
Math.abs(A[i] - j));
}
}
int res = Integer.MAX_VALUE;
for ( int j = 0 ; j <= M; j++)
res = Math.min(res, dp[n - 1 ][j]);
return res;
}
public static void main (String[] args)
{
int arr[] = { 55 , 77 , 52 , 61 , 39 , 6 , 25 , 60 , 49 , 47 };
int n = arr.length;
int target = 10 ;
System.out.println( "Minimum adjustment cost is "
+minAdjustmentCost(arr, n, target));
}
}
|
Python3
M = 100
def minAdjustmentCost(A, n, target):
dp = [[ 0 for i in range (M + 1 )]
for i in range (n)]
for j in range (M + 1 ):
dp[ 0 ][j] = abs (j - A[ 0 ])
for i in range ( 1 , n):
for j in range (M + 1 ):
dp[i][j] = 100000000
for k in range ( max (j - target, 0 ),
min (M, j + target) + 1 ):
dp[i][j] = min (dp[i][j], dp[i - 1 ][k] +
abs (A[i] - j))
res = 10000000
for j in range (M + 1 ):
res = min (res, dp[n - 1 ][j])
return res
arr = [ 55 , 77 , 52 , 61 , 39 ,
6 , 25 , 60 , 49 , 47 ]
n = len (arr)
target = 10
print ( "Minimum adjustment cost is" ,
minAdjustmentCost(arr, n, target),
sep = ' ' )
|
C#
using System;
class GFG {
public static int M = 100;
static int minAdjustmentCost( int []A, int n,
int target)
{
int [,] dp = new int [n,M + 1];
for ( int j = 0; j <= M; j++)
dp[0,j] = Math.Abs(j - A[0]);
for ( int i = 1; i < n; i++)
{
for ( int j = 0; j <= M; j++)
{
dp[i,j] = int .MaxValue;
int k = Math.Max(j - target, 0);
for ( ; k <= Math.Min(M, j +
target); k++)
dp[i,j] = Math.Min(dp[i,j],
dp[i - 1,k]
+ Math.Abs(A[i] - j));
}
}
int res = int .MaxValue;
for ( int j = 0; j <= M; j++)
res = Math.Min(res, dp[n - 1,j]);
return res;
}
public static void Main ()
{
int []arr = {55, 77, 52, 61, 39,
6, 25, 60, 49, 47};
int n = arr.Length;
int target = 10;
Console.WriteLine( "Minimum adjustment"
+ " cost is "
+ minAdjustmentCost(arr, n, target));
}
}
|
Javascript
<script>
let M = 100;
function minAdjustmentCost(A, n, target)
{
let dp = new Array(n);
for (let i = 0; i < n; i++)
{
dp[i] = new Array(n);
for (let j = 0; j <= M; j++)
{
dp[i][j] = 0;
}
}
for (let j = 0; j <= M; j++)
dp[0][j] = Math.abs(j - A[0]);
for (let i = 1; i < n; i++)
{
for (let j = 0; j <= M; j++)
{
dp[i][j] = Number.MAX_VALUE;
let k = Math.max(j-target,0);
for ( ; k <= Math.min(M,j+target); k++)
dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] +
Math.abs(A[i] - j));
}
}
let res = Number.MAX_VALUE;
for (let j = 0; j <= M; j++)
res = Math.min(res, dp[n - 1][j]);
return res;
}
let arr = [55, 77, 52, 61, 39, 6, 25, 60, 49, 47];
let n = arr.length;
let target = 10;
document.write( "Minimum adjustment cost is "
+minAdjustmentCost(arr, n, target));
</script>
|
PHP
<?php
$M = 100;
function minAdjustmentCost( $A , $n , $target )
{
global $M ;
$dp = array ( array ());
for ( $j = 0; $j <= $M ; $j ++)
$dp [0][ $j ] = abs ( $j - $A [0]);
for ( $i = 1; $i < $n ; $i ++)
{
for ( $j = 0; $j <= $M ; $j ++)
{
$dp [ $i ][ $j ] = PHP_INT_MAX;
for ( $k = max( $j - $target , 0);
$k <= min( $M , $j + $target );
$k ++)
$dp [ $i ][ $j ] = min( $dp [ $i ][ $j ],
$dp [ $i - 1][ $k ] +
abs ( $A [ $i ] - $j ));
}
}
$res = PHP_INT_MAX;
for ( $j = 0; $j <= $M ; $j ++)
$res = min( $res , $dp [ $n - 1][ $j ]);
return $res ;
}
$arr = array (55, 77, 52, 61, 39,
6, 25, 60, 49, 47);
$n = count ( $arr );
$target = 10;
echo "Minimum adjustment cost is "
, minAdjustmentCost( $arr , $n , $target );
?>
|
Output
Minimum adjustment cost is 75
Time Complexity: O(n*m2)
Auxiliary Space: O(n *m)
Efficient approach : Space optimization
In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.
Implementation steps:
- Create a 1D vector dp of size m+1.
- Set a base case by initializing the values of DP.
- Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
- Now Create a temporary 1d vector prev_dp used to store the current values from previous computations.
- After every iteration assign the value of prev_dp to dp for further iteration.
- Initialize a variable res to store the final answer and update it by iterating through the Dp.
- At last return and print the final answer stored in res.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
#define M 100
int minAdjustmentCost( int A[], int n, int target)
{
int dp[M + 1];
for ( int j = 0; j <= M; j++)
dp[j] = abs (j - A[0]);
for ( int i = 1; i < n; i++)
{
int prev_dp[M + 1];
memcpy (prev_dp, dp, sizeof (dp));
for ( int j = 0; j <= M; j++)
{
dp[j] = INT_MAX;
for ( int k = max(j - target, 0); k <= min(M, j + target); k++)
dp[j] = min(dp[j], prev_dp[k] + abs (A[i] - j));
}
}
int res = INT_MAX;
for ( int j = 0; j <= M; j++)
res = min(res, dp[j]);
return res;
}
int main()
{
int arr[] = {55, 77, 52, 61, 39, 6, 25, 60, 49, 47};
int n = sizeof (arr) / sizeof (arr[0]);
int target = 10;
cout << "Minimum adjustment cost is "
<< minAdjustmentCost(arr, n, target) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class MinimumAdjustmentCost {
static final int M = 100 ;
static int minAdjustmentCost( int [] A, int n, int target) {
int [] dp = new int [M + 1 ];
for ( int j = 0 ; j <= M; j++) {
dp[j] = Math.abs(j - A[ 0 ]);
}
for ( int i = 1 ; i < n; i++) {
int [] prev_dp = Arrays.copyOf(dp, dp.length);
for ( int j = 0 ; j <= M; j++) {
dp[j] = Integer.MAX_VALUE;
for ( int k = Math.max(j - target, 0 ); k <= Math.min(M, j + target); k++) {
dp[j] = Math.min(dp[j], prev_dp[k] + Math.abs(A[i] - j));
}
}
}
int res = Integer.MAX_VALUE;
for ( int j = 0 ; j <= M; j++) {
res = Math.min(res, dp[j]);
}
return res;
}
public static void main(String[] args) {
int [] arr = { 55 , 77 , 52 , 61 , 39 , 6 , 25 , 60 , 49 , 47 };
int n = arr.length;
int target = 10 ;
System.out.println( "Minimum adjustment cost is " + minAdjustmentCost(arr, n, target));
}
}
|
Python3
def min_adjustment_cost(A, n, target):
M = 100
dp = [ 0 ] * (M + 1 )
for j in range (M + 1 ):
dp[j] = abs (j - A[ 0 ])
for i in range ( 1 , n):
prev_dp = dp[:]
for j in range (M + 1 ):
dp[j] = float ( 'inf' )
for k in range ( max (j - target, 0 ), min (M, j + target) + 1 ):
dp[j] = min (dp[j], prev_dp[k] + abs (A[i] - j))
res = float ( 'inf' )
for j in range (M + 1 ):
res = min (res, dp[j])
return res
if __name__ = = "__main__" :
arr = [ 55 , 77 , 52 , 61 , 39 , 6 , 25 , 60 , 49 , 47 ]
n = len (arr)
target = 10
print ( "Minimum adjustment cost is" , min_adjustment_cost(arr, n, target))
|
C#
using System;
class Program
{
const int M = 100;
static int MinAdjustmentCost( int [] A, int n, int target)
{
int [] dp = new int [M + 1];
for ( int j = 0; j <= M; j++)
{
dp[j] = Math.Abs(j - A[0]);
}
for ( int i = 1; i < n; i++)
{
int [] prevDp = ( int [])dp.Clone();
for ( int j = 0; j <= M; j++)
{
dp[j] = int .MaxValue;
for ( int k = Math.Max(j - target, 0); k <= Math.Min(M, j + target); k++)
{
dp[j] = Math.Min(dp[j], prevDp[k] + Math.Abs(A[i] - j));
}
}
}
int res = int .MaxValue;
for ( int j = 0; j <= M; j++)
{
res = Math.Min(res, dp[j]);
}
return res;
}
static void Main()
{
int [] arr = { 55, 77, 52, 61, 39, 6, 25, 60, 49, 47 };
int n = arr.Length;
int target = 10;
Console.WriteLine( "Minimum adjustment cost is " + MinAdjustmentCost(arr, n, target));
}
}
|
Javascript
const M = 100;
function minAdjustmentCost(A, n, target) {
let dp = new Array(M + 1);
for (let j = 0; j <= M; j++)
dp[j] = Math.abs(j - A[0]);
for (let i = 1; i < n; i++)
{
let prev_dp = [...dp];
for (let j = 0; j <= M; j++)
{
dp[j] = Number.MAX_VALUE;
for (let k = Math.max(j - target, 0); k <= Math.min(M, j + target); k++)
dp[j] = Math.min(dp[j], prev_dp[k] + Math.abs(A[i] - j));
}
}
let res = Number.MAX_VALUE;
for (let j = 0; j <= M; j++)
res = Math.min(res, dp[j]);
return res;
}
let arr = [55, 77, 52, 61, 39, 6, 25, 60, 49, 47];
let n = arr.length;
let target = 10;
console.log( "Minimum adjustment cost is " + minAdjustmentCost(arr, n, target));
|
Output
Minimum adjustment cost is 75
Time Complexity: O(n*m2)
Auxiliary Space: O(m)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Oct, 2023
Like Article
Save Article