码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum Adjustment Cost

时间:2015-02-23 15:26:38      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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.

 1 public class Solution {
 2     /**
 3      * @param A: An integer array.
 4      * @param target: An integer.
 5      */
 6     public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
 7         if(A == null || A.size() < 2) return -1;
 8         
 9         //get max value of array
10         int max = 0;
11         for(int i = 0; i < A.size(); i ++)
12             max = Math.max(max, A.get(i));
13             
14         int[][] arr = new int[A.size()][max + 1];
15         
16         //init: dp[0][v] = |A[0] - v| 
17         for(int i = 0; i <= max; i ++)
18             arr[0][i] = Math.abs(i - A.get(0));
19             
20         //dp[i][v] = min(dp[i - 1][v - target … v + target]) + |A[i] - v|
21         for(int j = 1; j < A.size(); j ++){
22             for(int i = 0; i <= max; i ++){
23                 int minPre = Integer.MAX_VALUE;
24                 for(int k = Math.max(0, i - target); k <= Math.min(max, i + target); k ++)
25                     minPre = Math.min(minPre, arr[j - 1][k]);
26                 arr[j][i] = Math.abs(i - A.get(j)) + minPre;
27             }
28         }
29         int result = Integer.MAX_VALUE;
30         for(int i = 0; i <= max; i ++)
31             result = Math.min(result, arr[A.size() - 1][i]);
32             
33         return result;
34     }
35 }

 

Minimum Adjustment Cost

标签:

原文地址:http://www.cnblogs.com/reynold-lei/p/4298029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!