#91 Minimum Adjustment Cost

探讨如何通过调整数组中相邻整数间的差值不超过给定目标数,以最小化调整成本。利用动态规划方法,定义dp矩阵来求解最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

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.

题目思路:

这题的关键在于怎么去定义dp matrix。这里定义dp[i][j],i表示A中index为i的那个数,j表示那个数的value。由于value是有限的(0 ~ 100),所以对于每个i,我们都可以遍历一遍0~100去看这个cost各是多少。最后,由于最后一个数的value不确定,我们需要遍历dp[A.size() - 1][0...100]去找到最小cost的值。

Mycode(AC = 25ms):

class Solution {
public:
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    int MinAdjustmentCost(vector<int> A, int target) {
        // write your code here
        if (A.size() == 0) {
            return 0;
        }
        
        vector<vector<int>> cost(A.size(), vector<int>(101, 0));
        
        // cost[i][j] denotes the number at index i in A
        // the number's value is j
        
        // initialize the cost for first number (index i)
        for (int i = 0; i <= 100; i++) {
            cost[0][i] = abs(i - A[0]);
        }
        
        int min_cost = INT_MAX;
        
        for (int i = 1; i < A.size(); i++) {
            
            for (int j = 0; j <= 100; j++) {
                cost[i][j] = INT_MAX;
                
                // if number at index i and i - 1 
                // meets requirement, then find the min
                // cost for all the possible i and i - 1
                for (int k = 0; k <= 100; k++) {
                    if (abs(j - k) <= target) {
                        cost[i][j] = min(cost[i][j], cost[i - 1][k] + abs(A[i] - j));
                    }
                }
            }
        }
        
        // traverse through last number value of 0 ~ 100
        // and find the min cost
        for (int i = 0; i <= 100; i++) {
            if (cost[A.size() - 1][i] < INT_MAX) {
                min_cost = min(min_cost, cost[A.size() - 1][i]);
            }
        }
        
        return min_cost;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值