Lintcode - Minimum Adjustment Cost

Given an integer array, adjust each integers so that the difference of every adjcent 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 [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.

思路:

d[i][j] 代表第i個數調整到j時的最小cost。

for each d[i][j], minimum cost = minimum cost d[i-1][j-target ... j+target] + abs(A[i]-j)

所以用三重循環,i,j,j-target...j+target

Update, less code:

    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        // write your code here
        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;
    }
}

    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < A.size(); i++) {
            int val = A.get(i);
            max = Math.max(max, val);
        }
        
        int range = max+1;
        int[][] cost = new int[A.size()][range];
        int curMin = 0;
        for (int i = 0; i < range; i++) {
            cost[0][i] = Math.abs(A.get(0)-i);
        }
        
        for (int i = 1; i < A.size(); i++) {
            curMin = Integer.MAX_VALUE;
            for (int j = 0; j < range; j++) {
                cost[i][j] = Integer.MAX_VALUE;
                for (int diff = -1 * target; diff <= target; diff++) {
                    int lastCol = j+diff;
                    if (lastCol < 0) {
                        continue;
                    }
                    if (lastCol >= range) {
                        break;
                    }
                    int curAdj = Math.abs(A.get(i) - j);
                    int totalAdj = cost[i-1][lastCol] + curAdj;
                    cost[i][j] = Math.min(totalAdj, cost[i][j]);
                    curMin = Math.min(curMin, totalAdj);
                }
            }
        }
        return curMin;
    }


發佈了172 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章