题目
给定一个数组,将其分为 k 段,对每一段求和,并求得最大值 max。
求在所有的分段方案中,max 的最小值。
代码
public class Main {
public static int getMax(int array[], int n) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (array[i] > max) max = array[i];
}
return max;
}
public static int getSum(int array[], int n) {
int total = 0;
for (int i = 0; i < n; i++)
total += array[i];
return total;
}
/**
* 当所有段的最大值为 maxLengthPerPainter 时,返回最少可以将其分为多少段
*/
public static int getRequiredPainters(int array[], int n, int maxLengthPerPainter) {
int total = 0, numPainters = 1;
for (int i = 0; i < n; i++) {
total += array[i];
if (total > maxLengthPerPainter) {
total = array[i];
numPainters++;
}
}
return numPainters;
}
public static int binarySearch(int array[], int n, int k) {
/**
* low 代表所有分段中的最小段的值
* high 代表所有分段中的最大段的值
*/
int low = getMax(array, n);
int high = getSum(array, n);
while (low < high) {
int mid = low + (high - low) / 2;
int requiredPainters = getRequiredPainters(array, n, mid);
if (requiredPainters <= k)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void main(String[] args) {
int k = 3;
int[] a = {9, 4, 5, 12, 3, 5, 8, 11, 0};
System.out.println(binarySearch(a, a.length, k));
}
}