[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 isB, 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.

Note

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

动态规划,dp[i][j]表示把第i个数调整为j后的最小代价,状态转移方程为:

dp[i][j] = min(dp[i][j], dp[i-1][k] + abs(A[i] - j));

其中,k表示上一个数调整后的数值,范围在max(0, j - target) 与 min(100, j + target) 之间。

 1 class Solution {
 2 public:
 3     /**
 4      * @param A: An integer array.
 5      * @param target: An integer.
 6      */
 7     int MinAdjustmentCost(vector<int> A, int target) {
 8         // write your code here
 9         if (A.empty()) return 0;
10         vector<vector<int>> dp(A.size(), vector<int>(101, INT_MAX));
11         for (int i = 0; i <= 100; ++i) {
12             dp[0][i] = abs(A[0] - i);
13         }
14         for (int i = 1; i < A.size(); ++i) {
15             for (int j = 0; j <= 100; ++j) {
16                 for (int k = max(0, j - target); k <= min(100, j + target); ++k)
17                     dp[i][j] = min(dp[i][j], dp[i-1][k] + abs(A[i] - j));
18             }
19         }
20         int res = INT_MAX;
21         for (int i = 0; i <= 100; ++i) {
22             res = min(res, dp[A.size()-1][i]);
23         }
24         return res;
25     }
26 };

 

posted @ 2015-06-03 12:55  Eason Liu  阅读(532)  评论(0编辑  收藏  举报