problem:
Given an array which consists of non-negative integers and a integer m, you can split the array into m non-empty continuo US subarrays. Write a algorithm to minimize the largest sum among these m subarrays.
Note:
If N is the length of an array, assume the following constraints is satisfied:1≤n≤1000 1≤m≤min (n)
Example:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
Explanation: There is four
ways-split nums into TW o subarrays.
The best-of-the-is-to-split it into [7,2,5] and [10,8], where the largest sum among the "the" and "is
" only 18.
algorithm:The main test instructions is to divide an array of n elements into m intervals, so that the maximum values in the interval and in the middle are minimized. The problem can be solved by means of two-point answer method. By gradually dividing the integers in the 0~2147483647, and then judging whether the array can be divided into m intervals and each interval is less than the new two points, we can gradually approximate the answer. When the condition is not satisfied, the resulting minimum value is the answer that is solved. Because there are only a finite number of integers, the two-part answer can be done in constant time. For each intermediate value, it is necessary to iterate through the array to determine if the value satisfies test instructions, and an O (n) time is required, so the total time complexity is O (n).
Code:
BOOL Is_valid (vector<int>& nums, int m, unsigned mid) {
unsigned sum = 0;
int count = 0;
for (int i = 0; i < nums.size (); ++i) {
if (sum + nums[i] <= mid) {
sum + = Nums[i];
}
else {
count + = 1;
if (Nums[i] > mid) return false;
sum = nums[i];
if (count = = m) return false;
}
}
return count < m;
}
Class Solution {public
:
int Splitarray (vector<int>& nums, int m) {
unsigned minn= 1, MAXN = 2147 483647, mid;
while (Minn < MAXN) {
mid = (MINN+MAXN)/2;
if (Is_valid (Nums, M, mid)) MAXN = mid;
else Minn = mid+1;
}
return minn;
}
;