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;
}
};