Minimum Adjustment Cost

时间:2023-03-09 07:08:28
Minimum Adjustment Cost

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

Note: You can assume each number in the array is a positive integer and not greater than 100.

Example

Given A = [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.

分析:

首先,对于数组里的每个数,它最终的值不可能大于这个数组里最大的数(max)。所以,每个数的范围只能是从1到max. 如果第i个数取的值是j, 那么对于第i - 1个数,它能取的范围是不是只能是Math.max(1, j - target) 到 Math.min(j + target, max)。

如果用cost[i][j] 表示第i个数取p那个值时从第0个数到第i个数的total cost, 那么 cost[i][j] = Math.min(Math.abs(j - A.get(i)) + costs[i - 1][k]),  Math.max(1, j - target)  <= k <= Math.min(j + target, max) and j - A.get(i))

备注:最好自己创建一个二维costs表,自己安照下面的代码走一遍就明白了。

 public class Solution {
/**
* cnblogs.com/beiyeqingteng/
*/
public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
if (A == null || A.size() == ) return ;
int max = getMax(A);
int[][] costs = new int[A.size()][max + ]; for (int i = ; i < costs.length; i++) {
for (int j = ; j <= max; j++) {
costs[i][j] = Integer.MAX_VALUE;
if (i == ) {
// for the first number in the array, we assume it ranges from 1 to max;
costs[i][j] = Math.abs(j - A.get(i));
} else {
// for the number A.get(i), if we change it to j, then the minimum total cost
// is decided by Math.abs(j - A.get(i)) + costs[i - 1][k], and the range of
// k is from Math.max(1, j - target) to Math.min(j + target, max)
for (int k = Math.max(, j - target); k <= Math.min(j + target, max); k++) {
costs[i][j] = Math.min(costs[i][j], Math.abs(j - A.get(i)) + costs[i - ][k]);
}
}
}
} int min = Integer.MAX_VALUE;
for (int i = ; i < costs[].length; i++) {
min = Math.min(min, costs[costs.length - ][i]);
}
return min;
} private int getMax(ArrayList<Integer> A) {
int max = A.get();
for (int i = ; i < A.size(); i++) {
max = Math.max(max, A.get(i));
}
return max;
}
}

转载请注明出处: cnblogs.com/beiyeqingteng/