标签:
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]|
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
.
分析:
首先,对于数组里的每个数,它最终的值不可能大于这个数组里最大的数。第二,对于第一个数,costs = Math.abs(newValue - A[0]), 但是对于后面的数,我们用costs[i][j]表示对于前(i + 1) 个值,如果第(i + 1)这个值 (即A[i])的新值是 J 的时候的total cost. 那么 cost[i][j] = Math.min(costs[i][j], 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)) 指的是A[i] 变成 j的cost.
备注:最好自己创建一个二维costs表,自己安照下面的代码走一遍就明白了。
1 public class Solution { 2 /** 3 * cnblogs.com/beiyeqingteng/ 4 */ 5 public int MinAdjustmentCost(ArrayList<Integer> A, int target) { 6 if (A == null || A.size() == 0) return 0; 7 int max = getMax(A); 8 int[][] costs = new int[A.size()][max + 1]; 9 10 for (int i = 0; i < costs.length; i++) { 11 for (int j = 1; j <= max; j++) { 12 costs[i][j] = Integer.MAX_VALUE; 13 if (i == 0) { 14 // for the first number in the array, we assume it ranges from 1 to max; 15 costs[i][j] = Math.abs(j - A.get(i)); 16 } else { 17 // for the number A.get(i), if we change it to j, then the minimum total cost 18 // is decided by Math.abs(j - A.get(i)) + costs[i - 1][k], and the range of 19 // k is from Math.max(1, j - target) to Math.min(j + target, max) 20 for (int k = Math.max(1, j - target); k <= Math.min(j + target, max); k++) { 21 costs[i][j] = Math.min(costs[i][j], Math.abs(j - A.get(i)) + costs[i - 1][k]); 22 } 23 } 24 } 25 } 26 27 int min = Integer.MAX_VALUE; 28 for (int i = 1; i < costs[0].length; i++) { 29 min = Math.min(min, costs[costs.length - 1][i]); 30 } 31 return min; 32 } 33 34 private int getMax(ArrayList<Integer> A) { 35 int max = A.get(0); 36 for (int i = 1; i < A.size(); i++) { 37 max = Math.max(max, A.get(i)); 38 } 39 return max; 40 } 41 }
转载请注明出处: cnblogs.com/beiyeqingteng/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5626089.html