国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Lintcode: Minimum Adjustment Cost

2019-11-14 23:34:54
字體:
來源:轉載
供稿:網(wǎng)友
Lintcode: Minimum Adjustment Cost
1 Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a given number target.2 3 If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]| 4 5 Note6 You can assume each number in the array is a positive integer and not greater than 1007 8 Example9 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.

這道題要看出是背包問題,不容易,跟FB一面 paint house很像,比那個難一點

定義res[i][j] 表示前 i個number with 最后一個number是j,這樣的minimum adjusting cost

如果第i-1個數(shù)是j, 那么第i-2個數(shù)只能在[lowerRange, UpperRange]之間,lowerRange=Math.max(0, j-target), upperRange=Math.min(99, j+target),

這樣的話,transfer function可以寫成:

for (int p=lowerRange; p<= upperRange; p++) {

  res[i][j] = Math.min(res[i][j], res[i-1][p] + Math.abs(j-A.get(i-1)));

}

 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         // write your code here 8         int[][] res = new int[A.size()+1][100]; 9         for (int j=0; j<=99; j++) {10             res[0][j] = 0;11         }12         for (int i=1; i<=A.size(); i++) {13             for (int j=0; j<=99; j++) {14                 res[i][j] = Integer.MAX_VALUE;15                 int lowerRange = Math.max(0, j-target);16                 int upperRange = Math.min(99, j+target);17                 for (int p=lowerRange; p<=upperRange; p++) {18                     res[i][j] = Math.min(res[i][j], res[i-1][p]+Math.abs(j-A.get(i-1)));19                 }20             }21         }22         int result = Integer.MAX_VALUE;23         for (int j=0; j<=99; j++) {24             result = Math.min(result, res[A.size()][j]);25         }26         return result;27     }28 }


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 漯河市| 赫章县| 漳平市| 乌拉特后旗| 甘谷县| 嘉善县| 乌海市| 连州市| 武川县| 张家口市| 平南县| 漯河市| 锡林浩特市| 郁南县| 娄底市| 涞源县| 台北市| 合江县| 武宁县| 康马县| 达拉特旗| 大姚县| 彭山县| 金山区| 呼和浩特市| 鄂伦春自治旗| 如皋市| 电白县| 福州市| 淮阳县| 石首市| 孙吴县| 桐庐县| 乌兰察布市| 龙州县| 教育| 循化| 清镇市| 青冈县| 霸州市| 建平县|