LintCode 91: Minimum Adjustment Cost (DP经典题)

  1. 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
Example 1:
Input: [1,4,2,3], target=1
Output: 2

Example 2:
Input: [3,5,4,7], target=2
Output: 1

Notice
You can assume each number in the array is a positive integer and not greater than 100.

解法1:DP
思路:dp[i][j]为前i个元素中最后一个元素以高度j(1<=j<=100)结束的最优值,则第i-1个元素应该是在j-target到j+target中取,所以
dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(j - A[i - 1])); //k=[j-target, j+target]
注意,dp[i][j]取决于dp[i - 1][k] + abs(j - A[i - 1]), k=[j-target, j+target]中最小的那个。第i-1个元素取高度k,第i个元素取高度j,所以要加上abs(j-A[i-1])。

代码如下:

class Solution {
public:
    /*
     * @param A: An integer array
     * @param target: An integer
     * @return: An integer
     */
    int MinAdjustmentCost(vector<int> &A, int target) {
        int n = A.size();
        if (n == 0 ) return 0;
        int result = INT_MAX;
        
        vector<vector<int>> dp(n + 1, vector<int>(100 + 1, INT_MAX));
        for (int i = 0; i <= 100; ++i) {
            dp[0][i] = 0;
        }
        
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= 100; ++j) {
                int lowRange = max(1, j - target);
                int upperRange = min(100, j + target);
                for (int k = lowRange; k <= upperRange; ++k) {
                    dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(j - A[i - 1])); 
                    //abs(k - A[i - 1])); is also OK? should be abs(j - A[i - 1])?
                }
            }
        }
        
        for (int i = 1; i <= 100; ++i) {
            result = min(result, dp[n][i]);
        }
            
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值