410 Split Array Largest Sum The maximum value of the split array

Given an array of non-negative integers and an integer m, you need to divide the array into m non-empty contiguous subarrays. Design an algorithm to minimize the maximum value of the sums of the m subarrays.
Note:
The array length n satisfies the following conditions:
    1 ≤ n ≤ 1000
    1 ≤ m ≤ min(50, n)
Example:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
18
Explanation:
total There are four ways to split nums into 2 sub-arrays.
The best way is to divide it into [7, 2, 5] and [10, 8],
because the sum of the two sub-arrays has a maximum value of 18 at this time, which is the smallest in all cases.
See: https://leetcode.com/problems/split-array-largest-sum/description/
C++:

class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        long long left = 0, right = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            left = max((int)left, nums[i]);
            right += nums[i];
        }
        while (left < right)
        {
            long long mid = left + (right - left) / 2;
            if (can_split(nums, m, mid))
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }
        return left;
    }
    bool can_split(vector<int>& nums, int m, int sum)
    {
        int cnt = 1, curSum = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            curSum += nums[i];
            if (curSum > sum)
            {
                curSum = num[i];
                ++cnt;
                if (cnt > m)
                {
                    return false;
                }
            }
        }
        return true;
    }
};

 Reference: https://www.cnblogs.com/grandyang/p/5933787.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324449952&siteId=291194637