Description:
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisfied:
- 1 ≤ n ≤ 1000
- 1 ≤ m ≤ min(50, n)
Examples:
Input: nums = [7,2,5,10,8] m = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
解题思路:
看到这道题第一想法是排序,让数组里的数字从小到大排列,然后再进行排列。然后看到题目意思是并不用排序,只用分块就好。问题来了,怎么分块呢,遍历找出所有的m个组合并不太实际。借助了别人的思路,利用二分搜索来做这道题。据上述例子[7,2,5,10,8],找出最大的一个数10,以及整个数组的和32,则解在[10,32]里出现。取mid = 21,找到7,2,5 和 10,8。可以分则降低mid,取mid = 15,找到7,2,5和10和8,发现数组大于2,则升高mid,取mid = (15+21)/2 ……到最后直到left>=right 循环结束。返回的left值就是解,这是因为right是保证了倒数第二次的数组能满足的情况的值,当到最后一个数字,则需要left来满足增大mid
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int left = 0, right = 0;
for(int i = 0; i < nums.size(); i++){
left = max(left, nums[i]);
right += nums[i];
}
while(left < right){
int mid = left + (right - left)/2;
if(is_ok(nums, m, mid)) right = mid;
else left = mid+1;
}
return left;
}
bool is_ok(vector<int>& nums, int m, int mid){
int array_count = 1;
int temp_sum = 0;
for(int i = 0; i < nums.size(); i++){
temp_sum += nums[i];
if(temp_sum > mid){
array_count++;
temp_sum = nums[i];
if(array_count > m) return false;
}
}
return true;
}
};