题目

最小调整代价

给一个整数数组,调整每个数的大小,使得相邻的两个数的差小于一个给定的整数target,调整每个数的代价为调整前后的差的绝对值,求调整代价之和最小是多少。

样例

对于数组[1, 4, 2, 3]和target=1,最小的调整方案是调整为[2, 3, 2, 3],调整代价之和是2。返回2。

注意

你可以假设数组中每个整数都是正整数,且小于等于100

解题

参考博客 比较复杂

方法一

用1 到100内的数,替换数组中的每位数字

public class Solution {
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    public static int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        // write your code here
        if (A == null) {
            return 0;
        }
        
        return rec(A, new ArrayList<Integer>(A), target, 0);
    }
    
    /*
     * SOL 1:
     * 最普通的递归方法。
     * */
    public static int rec(ArrayList<Integer> A, ArrayList<Integer> B, int target, int index) {
        int len = A.size();
        if (index >= len) {
            // The index is out of range.
            return 0;
        }
        
        int dif = 0;
        
        int min = Integer.MAX_VALUE;
        
        // If this is the first element, it can be from 1 to 100;
        for (int i = 0; i <= 100; i++) {
            if (index != 0 && Math.abs(i - B.get(index - 1)) > target) {
                continue;
            }
            
            B.set(index, i);// index位置的值更新为 i 
            dif = Math.abs(i - A.get(index)); // 记录差值
            dif += rec(A, B, target, index + 1); // 中间迭代
            min = Math.min(min, dif); // 计算最小值
            
            // 回溯
            B.set(index, A.get(index));
        }
        
        return min;
    }
}


    
View Code

相关文章:

  • 2021-09-01
  • 2021-09-03
  • 2021-07-12
  • 2021-11-13
  • 2022-01-19
  • 2022-12-23
  • 2021-09-17
  • 2021-08-13
猜你喜欢
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-17
  • 2022-01-07
  • 2022-02-17
相关资源
相似解决方案