一、题目描述
篮球(5V5)比赛中,每个球员拥有一个战斗力,每个队伍的所有球员战斗力之和为该队伍的总体战斗力。现有 10 个球员准备分为两队进行训练赛,教练希望 2 个队伍的战斗力差值能够尽可能的小,以达到最佳训练效果。给出 10 个球员的战斗力,如果你是教练,你该如何分队,才能达到最佳训练效果?请输出该分队方案下的最小战斗力差值。
二、输入描述
10 个篮球队员的战斗力(整数,范围[1,10000]),战斗力之间用空格分隔,如:10 9 8 7 6 5 4 3 2 1 不需要考虑异常输入的场景。
三、输出描述
最小的战斗力差值,如:1
3.1 示例1
输入:
10 9 8 7 6 5 4 3 2 1
输出:
1
四、代码实现
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
public class Day06 {
public int minMinus(String input) {
// 处理异常
if (input.isEmpty()) {
return -1;
}
// 处理输入
int[] arr = Arrays.stream(input.split(" ")).mapToInt(Integer::parseInt).toArray();
if (arr.length == 1) {
return arr[0];
}
List<Integer> aList = new ArrayList<>(5);
List<Integer> bList = new ArrayList<>(5);
int aSum = 0;
int bSum = 0;
// 降序
int[] sortedArray = IntStream.of(arr)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
if (sortedArray.length == 2) {
return sortedArray[1] - sortedArray[0];
}
for (int j : sortedArray) {
if (aSum >= bSum) {
bList.add(j);
bSum += j;
} else {
aList.add(j);
aSum += j;
}
}
int diff = Math.abs(aSum - bSum);
System.out.println("aList: " + aList + ", bList: " + bList + ", diff: " + diff);
return diff;
}
}
五、测试
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class Day06Test {
private static Day06 day06;
@BeforeAll
public static void setUp() {
day06 = new Day06();
}
@Test
void minMinus() {
int diff = day06.minMinus("10 9 8 7 6 5 4 3 2 1");
Assertions.assertEquals(diff, 1);
diff = day06.minMinus("10 10 10 7 10 5 1 9 2 10");
Assertions.assertEquals(diff, 0);
diff = day06.minMinus("10 10 10 7 10 5 6 9 2 10");
Assertions.assertEquals(diff, 3);
}
}
aList: [9, 8, 5, 4, 1], bList: [10, 7, 6, 3, 2], diff: 1
aList: [10, 10, 9, 7, 1], bList: [10, 10, 10, 5, 2], diff: 0
aList: [10, 10, 9, 7, 2], bList: [10, 10, 10, 6, 5], diff: 3