首页 技术 正文
技术 2022年11月13日
0 收藏 913 点赞 2,632 浏览 1318 个字
 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.

这道题要看出是背包问题,不容易,跟FB一面paint house很像,比那个难一点

定义res[i][j] 表示前 i个number with 最后一个number是j,这样的minimum adjusting cost

如果第i-1个数是j, 那么第i-2个数只能在[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)));

}

 public class Solution {
/**
* @param A: An integer array.
* @param target: An integer.
*/
public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
// write your code here
int[][] res = new int[A.size()+1][100];
for (int j=0; j<=99; j++) {
res[0][j] = 0;
}
for (int i=1; i<=A.size(); i++) {
for (int j=0; j<=99; j++) {
res[i][j] = Integer.MAX_VALUE;
int lowerRange = Math.max(0, j-target);
int upperRange = Math.min(99, j+target);
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)));
}
}
}
int result = Integer.MAX_VALUE;
for (int j=0; j<=99; j++) {
result = Math.min(result, res[A.size()][j]);
}
return result;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860