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.
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; } }
相关文章推荐
- Minimum Adjustment Cost
- [LintCode] Minimum Adjustment Cost
- lintcode minimum-adjustment-cost 最小调整代价
- LintCode "Minimum Adjustment Cost"
- lintcode:Minimum Adjustment Cost
- Lintcode - Minimum Adjustment Cost
- 【算法题】minimum-adjustment-cost
- Lintcode: Minimum Adjustment Cost
- [刷题]Minimum Adjustment Cost
- [Lintcode]Minimum Adjustment Cost
- Lintcode91 Minimum Adjustment Cost solution 题解
- #91 Minimum Adjustment Cost
- minimum adjustment cost
- lintcode:minimum adjustment cost 最小调整代价
- [LintCode]Minimum Adjustment Cost
- LintCode-Minimum Adjustment Cost
- [LintCode] Minimum Adjustment Cost
- lintcode-medium-Minimum Adjustment Cost
- hdoj 1385 Minimum Transport Cost(floyd 记录最短路径)
- HDOJ 1385 Minimum Transport Cost(dijkstar+字典路径||floyd+字典路径)