Find minimum adjustment cost of an array | PHP program to find minimum adjustment cost of an array ; Function to find minimum adjustment cost of an array ; dp [ i ] [ j ] stores minimal adjustment cost on changing A [ i ] to j ; handle first element of array separately ; do for rest elements of the array ; replace A [ i ] to j and calculate minimal adjustment cost dp [ i ] [ j ] ; initialize minimal adjustment cost to INT_MAX ; consider all k such that k >= max ( j - target , 0 ) and k <= min ( M , j + target ) and take minimum ; return minimum value from last row of dp table ; Driver Code
< ? 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 ) ; ? >