您的位置:首页 > 其它

Minimum Adjustment Cost

2015-02-23 14:07 92 查看
Given an integer array, adjust each integers so that the difference of every adjcent 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]|

Note

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.

public class Solution {
/**
* @param A: An integer array.
* @param target: An integer.
*/
public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
if(A == null || A.size() < 2) return -1;

//get max value of array
int max = 0;
for(int i = 0; i < A.size(); i ++)
max = Math.max(max, A.get(i));

int[][] arr = new int[A.size()][max + 1];

//init: dp[0][v] = |A[0] - v|
for(int i = 0; i <= max; i ++)
arr[0][i] = Math.abs(i - A.get(0));

//dp[i][v] = min(dp[i - 1][v - target … v + target]) + |A[i] - v|
for(int j = 1; j < A.size(); j ++){
for(int i = 0; i <= max; i ++){
int minPre = Integer.MAX_VALUE;
for(int k = Math.max(0, i - target); k <= Math.min(max, i + target); k ++)
minPre = Math.min(minPre, arr[j - 1][k]);
arr[j][i] = Math.abs(i - A.get(j)) + minPre;
}
}
int result = Integer.MAX_VALUE;
for(int i = 0; i <= max; i ++)
result = Math.min(result, arr[A.size() - 1][i]);

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: