Problem
Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
Notice
You can assume each number in the array is a positive integer and not greater than 100.
Example
Given [1,4,2,3]
and target = 1
, one of the solutions is [2,3,2,3]
, the adjustment cost is 2
and it's minimal.
Return 2
.
Note
Solution
public class Solution {
public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
int n = A.size(), res = Integer.MAX_VALUE, max = res;
int[][] dp = new int[n][101];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= 100; j++) {
dp[i][j] = i == 0 ? Math.abs(j - A.get(i)) : max;
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j <= 100; j++) {
for (int k = j-target; k <= j+target && k <= 100; k++) {
if (k >= 0 && dp[i-1][k] < max) dp[i][j] = Math.min(dp[i][j], dp[i-1][k]+Math.abs(j-A.get(i)));
}
}
}
for (int j = 0; j <= 100; j++) {
res = Math.min(res, dp[n-1][j]);
}
return res;
}
}
public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
int n = A.size();
int max = 0;
for (int i = 0; i < n; i++) {
max = Math.max(max, A.get(i));
}
int[][] d = new int[n][max+1];
for (int j = 0; j <= max; j++) {
d[0][j] = Math.abs(A.get(0) - j);
}
int curMin = 0;
for (int i = 1; i < n; i++) {
curMin = Integer.MAX_VALUE;
for (int j = 0; j <= max; j++) {
d[i][j] = Integer.MAX_VALUE;
for (int k = Math.max(0, j-target); k <= Math.min(max, j+target); k++) {
d[i][j] = Math.min(d[i][j], d[i-1][k] + Math.abs(A.get(i)-j));
curMin = Math.min(curMin, d[i][j]);
}
}
}
return curMin;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。