题目
示例1
输入:
30 12 25 8 19
输出:
15
示例2
输入:
10 12 25 8 19 8 6 4 17 19 20 30
输出:
-1
题解
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] strs = in.nextLine().split(" ");
int len = strs.length;
if (len > 8) {
System.out.println(-1);
return;
}
if (len == 8) {
int max = 0;
for (String s : strs) {
int a = Integer.parseInt(s);
if (a > max) {
max = a;
}
}
System.out.println(max);
return;
}
List<Integer> bricks = new ArrayList<>(len);
int sum = 0;
for (String s : strs) {
int num = Integer.parseInt(s);
bricks.add(num);
sum += num;
}
bricks.sort((o1, o2) -> o2 - o1);
int start = sum / 8;
int end = bricks.get(0);
start = (start == 0) ? 1 : start;
while (start <= end) {
int times = 0;
for (int value : bricks) {
times += value / start + ((value % start == 0) ? 0 : 1);
}
if (times <= 8) {
System.out.println(start);
return;
}
start++;
}
System.out.println(-1);
}
}
参考
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Integer> bag = new ArrayList<>();
int sum = 0;
while (in.hasNextInt()) {
int value = in.nextInt();
bag.add(value);
if (value == 0) {
continue;
}
sum += value;
}
if (bag.size() > 8) {
System.out.println(-1);
return;
}
if (bag.isEmpty()) {
System.out.println(0);
return;
}
bag.sort((o1, o2) -> o2 - o1);
if (bag.size() == 8) {
System.out.println(bag.get(0));
return;
}
int start = sum / 8;
int end = bag.get(0);
start = (start == 0) ? 1 : start;
for (; start <= end; start++) {
int times = 0;
boolean success = true;
for (int value : bag) {
times += value / start + ((value % start == 0) ? 0 : 1);
if (times > 8) {
success = false;
break;
}
}
if (!success) {
continue;
}
System.out.println(start);
return;
}
System.out.println(-1);
}
}
https://blog.csdn.net/weixin_52908342/article/details/135549870