lintcode-medium-Minimum Adjustment Cost

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

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;
    }
}

 

以上是关于lintcode-medium-Minimum Adjustment Cost的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Minimum Size Subarray Sum

在python中,a+=a-=a的值是多少?

20170924 a20170924 a

a++和++a的区别

逻辑代数

python运算符