Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

分割数组的最大值

来自Leetcode第410题分割数组的最大值

给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。

示例:

1
2
3
4
5
6
7
8
9
10
11
输入:
nums = [7,2,5,10,8]
m = 2

输出:
18

解释:
一共有四种方法将nums分割为2个子数组。
其中最好的方式是将其分为[7,2,5] 和 [10,8],
因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。

二分查找

来自官方题解

「使……最大值尽可能小」是二分搜索题目常见的问法。

本题中,我们注意到:当我们选定一个值 xx,我们可以线性地验证是否存在一种分割方案,满足其最大分割子数组和不超过 xx。策略如下:

贪心地模拟分割的过程,从前到后遍历数组,用 \textit{sum}sum 表示当前分割子数组的和,\textit{cnt}cnt 表示已经分割出的子数组的数量(包括当前子数组),那么每当 \textit{sum}sum 加上当前值超过了 xx,我们就把当前取的值作为新的一段分割子数组的开头,并将 \textit{cnt}cnt 加 11。遍历结束后验证是否 \textit{cnt}cnt 不超过 mm

这样我们可以用二分查找来解决。二分的上界为数组 nums 中所有元素的和,下界为数组 nums 中所有元素的最大值。通过二分查找,我们可以得到最小的最大分割子数组和,这样就可以得到最终的答案了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public int splitArray(int[] nums, int m) {
int left = nums[0] , right = nums[0];
for(int i = 1 ; i < nums.length ; i++){
right += nums[i]; //right表示解范围的最大值
left = Math.max(left,nums[i]); //left为数组最大值,解范围的最小值
}
while (left < right){
int mid = left + (right - left) / 2;
if(check(nums,mid,m)) //如果这个最大和满足,就把这个最大和变小
right = mid;
else
left = mid + 1;
}
return left;
}

//判断给定的x,求数组的最大和
public boolean check(int[] nums,int x,int m){
int sum = 0;
int count = 1;
for(int i = 0 ; i < nums.length;i++){
if(sum + nums[i] > x){ //如果子数组和比给定的最大值还大
count ++; //重新开始计算子数组的和,并且计数+1
sum = nums[i];
}else //不超过子数组的和,就继续累加
sum += nums[i];
}
return count <= m; //如果不超过给定划分个数,就是符合的
}