consider all k such that k >= max ( j - target , 0 ) and k <= min ( M , j + target ) and take minimum
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 ) ) ; } }