题目描述:
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
.
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;
}
};