Problem :
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:
Given m satisfies the following constraint: 1 ≤ m ≤ length(nums) ≤ 14,000.
Example:
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.
**
Algorithm:
**
在网上查到一种很巧妙地方法,用的二分查找。题目把一个数组分成连续的m个数组,得到这些数组求和后的最大值,我们要找的就是这个最大值中的最小值。
很容易知道,这个最大值的范围肯定是在
(原数组的最大值,原数组求和)这个范围内的。
所以就以这两个值为left和right进行二分查找,每次查找都是看对于当前这个mid值作为数组的最大值中的最小值,这个数组是否能满足分成m份的要求,如果能,就说明我们要得到的值还在mid的左边,如果不行,说明在mid右边。
时间复杂度:二分插值O( logn)*判断是否满足条件O(n)=O(nlogn)
**
Code:
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
long long int left=0;
long long int right=0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>left)
left=nums[i];
right+=nums[i];
}
while(right>left)
{
long long int mid=(right+left)/2;
if(check(nums,m,mid))
{
right=mid;
}
else
left=mid+1;
}
return left;
}
bool check(vector<int>& nums,int m,int mid)
{
int c=1;
int sum=0;
for(int i=0;i<nums.size();i++)
{
sum+=nums[i];
if(sum>mid)
{
sum=nums[i];
c++;
if(c>m)
return false;
}
}
return true;
}
};