题目描述
【最短木板长度】
小明有 n 块木板,第 i ( 1 ≤ i ≤ n ) 块木板长度为 ai。
小明买了一块长度为 m 的木料,这块木料可以切割成任意块,
拼接到已有的木板上,用来加长木板。
小明想让最短的模板尽量长。
请问小明加长木板后,最短木板的长度可以为多少?
流程分析:
1. 只有一个板子的时候直接加;
2. 超过2个板子
从最小阶级差开始,一层一层计算:
可能一根都补不齐;
可能满足一部分;
可能补到当前最高板子还多;
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
if (n == 1) {
System.out.println(a[0] + m);
} else {
HashSet<Integer> hashSet = new HashSet<>();
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < a.length; i++) {
hashSet.add(a[i]);
if (map.containsKey(a[i])) {
map.put(a[i], map.get(a[i]) + 1);
} else {
map.put(a[i], 1);
}
}
ArrayList<Integer> list = new ArrayList<>(hashSet);
Collections.sort(list);
int minLength = list.get(0);
for (int i = 0; i < list.size(); i++) {
if (i == list.size() - 1) {
int avr = m / a.length;
if (avr > 0) {
minLength += avr;
}
break;
}
int num = list.get(i + 1) - list.get(i);
if (m >= num * map.get(list.get(i))) {
m -= num * map.get(list.get(i));
map.put(list.get(i + 1), map.get(list.get(i + 1)) + map.get(list.get(i)));
minLength = list.get(i + 1);
} else {
int avr = m / map.get(list.get(i));
if (avr != 0) {
minLength = list.get(i) + avr;
} else {
minLength = list.get(i);
}
break;
}
}
System.out.println(minLength);
}
}
}