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表,自己安照下面的代码走一遍就明白了。

 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/

posted @ 2016-06-29 10:57  北叶青藤  阅读(512)  评论(0编辑  收藏  举报