leetcode 410.Split Array Largest Sum(Hard)

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:
If n is the length of array, assume the following constraints are satisfied:

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ min(50, n)

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:
本题题意为将一个有n个元素的数组分为m个区间,使得区间和中的最大值最小。
本题可采用二分答案法进行求解。通过逐渐二分0~2147483647中的整数,然后判断数组能否划分成m个区间且每个区间的和均小于新的二分值,我们可以逐步逼近答案。
当条件无法满足时,所得到的最小值即为所求解的答案。
由于只有有限个整数,所以二分答案可在常数时间内进行。对于每一个中间值,需要遍历一遍数组判断该值是否满足题意,需要O(n)时间,因此,总的时间复杂度为O(n)。

Code:
bool is_valid(vector& 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& nums, int m) {
        unsigned minn= 1, maxn = 2147483647, mid;
        while (minn < maxn) {
            mid = (minn+maxn) / 2;
            if (is_valid(nums, m, mid)) maxn = mid;
            else minn = mid+1;
        }
        return minn;
    }
};


你可能感兴趣的:(leetcode 410.Split Array Largest Sum(Hard))