import java.util.ArrayList;
import java.util.List;
public class ShrinkingNumberLine4 {
public static int minimize(int[] point, int k) {
if (point == null || point.length == 0) {
return -1;
}
int incre = dfs(point, k, 1, point[0]+k, point[0]+k);
int decre = dfs(point, k, 1, point[0]-k, point[0]-k);
return Math.min(incre, decre);
}
public static int dfs(int[] point, int k, int idx, int min, int max) {
if (idx >= point.length) {
return max - min;
}
int min_incre = Math.min(min, point[idx] + k);
int max_incre = Math.max(max, point[idx] + k);
int incre = dfs(point, k, idx + 1, min_incre, max_incre);
int min_decre = Math.min(min, point[idx] - k);
int max_decre = Math.max(max, point[idx] - k);
int decre = dfs(point, k, idx + 1, min_decre, max_decre);
return Math.min(incre, decre);
}
public static int minimize2(int[] point, int k) {
if (point == null || point.length == 0) {
return -1;
}
List<Integer> list = new ArrayList<>();
return dfs2(point, k, 0, list);
}
public static int dfs2(int[] point, int k, int idx, List<Integer> list) {
if (idx >= point.length) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < list.size(); i++) {
min = Math.min(min, list.get(i));
max = Math.max(max, list.get(i));
}
//System.out.println(list.toString());
return max - min;
}
list.add(point[idx] + k);
int incre = dfs2(point, k, idx + 1, list);
list.remove(list.size() - 1);
list.add(point[idx] - k);
int decre = dfs2(point, k, idx + 1, list);
list.remove(list.size() - 1);
return Math.min(incre, decre);
}
public static void main(String[] args) {
System.out.println(minimize(new int[]{-3, 0, 1}, 3)); //3
System.out.println(minimize2(new int[]{-3, 0, 1}, 3)); //3
System.out.println(minimize(new int[]{4, 7, -7}, 5)); //4
System.out.println(minimize2(new int[]{4, 7, -7}, 5)); //4
System.out.println(minimize(new int[]{-100000, 100000}, 100000)); //0
System.out.println(minimize2(new int[]{-100000, 100000}, 100000)); //0
}
}
Shrinking Number Line
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 如题就是这样的: 问题 我出现的原因是这样:使用ant进行编译,安装进入,debug之后就打不了断点. 解决: 在...
- We are playing the Guess Game. The game is as follows: I ...
- Write an algorithm to determine if a number is "happy".A ...
- Write a program to find the n-th ugly number.Ugly numbers...
- 1.我是脾气好,但不是让你用来将就别人的。 明琪在微信里甩给我一句话:TMD老子以后要做一只高冷的刺猬!! 一向温...