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

 

Notice

You can assume each number in the array is a positive integer and not greater than100.

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.

 

感觉这个题挺难的,也是动态规划,看了别人写的半天才看懂

和背包问题差不多,用一个二维int数组,dp[i][j]记录A中前i个数,调整后最后一个数为j的时候,最小的adjustment cost

public class Solution {
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        // write your code here
        
        if(A == null || A.size() == 0)
            return 0;
        
        int size = A.size();
        
        int[][] dp = new int[size + 1][101];
        
        for(int i = 0; i < 101; i++)
            dp[0][i] = 0;
        
        for(int i = 1; i <= size; i++){
            for(int j = 0; j < 101; j++){
                dp[i][j] = Integer.MAX_VALUE;
                
                int upper = Math.min(100, j + target);
                int lower = Math.max(0, j - target);
                
                for(int k = lower; k <= upper; k++){
                    dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] + Math.abs(j - A.get(i - 1)));
                }
                
            }
        }
        
        int result = Integer.MAX_VALUE;
        for(int i = 0; i < 101; i++)
            result = Math.min(result, dp[size][i]);
        
        return result;
    }
}

 

posted @ 2016-03-31 13:38  哥布林工程师  阅读(160)  评论(0编辑  收藏  举报