[Lintcode]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]|

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.

分析:动态规划或者递归算法。动态规划:res[i][j]代表在i位置上换成j的cost。


public class Solution {
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        if(A == null || A.size() == 0) return 0;
        
        int[][] res = new int[A.size()][101];
        for(int i = 0; i < A.size(); i++) {
            for(int j = 1; j <= 100; j++) {
                res[i][j] = Integer.MAX_VALUE;
                if(i == 0) {
                    res[i][j] = Math.abs(A.get(i) - j);
                } else {
                    for(int k = 1; k <= 100; k++) {
                        if(Math.abs(j - k) > target) continue;
                        int diff = res[i - 1][k] + Math.abs(A.get(i) - j);
                        res[i][j] = Math.min(res[i][j], diff);
                    }
                }
            }
        }
        int ret = Integer.MAX_VALUE;
        for (int i = 1; i <= 100; i++) {
            ret = Math.min(ret, res[A.size() - 1][i]);
        }
         
        return ret;
    }
}

递归算法超时:

public class Solution {
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        if(A == null || A.size() == 0) return 0;
        
        return helper(A, new ArrayList<Integer>(A), 0, target);
    }
    
    int helper(ArrayList<Integer> A, ArrayList<Integer> B, int index, int target) {
        if(index >= B.size()) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int diff = 0;
        
        for(int i = 0; i <= 100; i++) {
            if(index != 0 && Math.abs(B.get(index - 1) - i) > target) {
                continue;
            }
            B.set(index, i);
            diff = Math.abs(A.get(index) - i);
            diff += helper(A, B, index + 1, target);
            min = Math.min(min, diff);
            B.set(index, A.get(index));
        }
        
        return min;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值