码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum Adjustment Cost

时间:2017-08-06 15:05:13      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:arraylist   背包   问题   ima   个数   背包问题   should   not   adjust   

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 than 100. Have you met this question in a real interview? Yes Example Given [1,4,2,3] and target = 1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and its minimal. Return 2.

这道题要看出是背包问题,不容易,跟FB一面 paint house很像,比那个难一点

定义res[i][j] 表示前 i个number with 最后一个number是j,这样的minimum adjusting cost

public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        // write your code here
        // 前i-1 个数调整后并且第i-1个数调整为j的cost
        int n = A.size();
        int[][] f = new int[n + 1][101];
        
        // initialize
        for (int i = 0; i <= 100; i++) {
            f[0][i] = 0;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= 100; j++) {
                f[i][j] = Integer.MAX_VALUE;
            }
        }
        //
        //function
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= 100; j++) {
                for (int k = 0; k <= 100; k++) {
                    if (Math.abs(j - k) <= target) {
                        
                            f[i][k] = Math.min(f[i][k], f[i - 1][j] + Math.abs(A.get(i - 1) - k));
                        
                        
                    }
                }
            }
        }
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i <= 100; i++) {
            ans = Math.min(ans, f[n][i]);
        }
        return ans;
    }

  

Minimum Adjustment Cost

标签:arraylist   背包   问题   ima   个数   背包问题   should   not   adjust   

原文地址:http://www.cnblogs.com/apanda009/p/7294627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!