410. Split Array Largest Sum

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了410. Split Array Largest Sum相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        int _max = -1, _sum = 0;
        for (auto n : nums) {
            if (n > _max)   _max = n;
            _sum += n;
        }
        int i = _max, j = _sum;
        while (i < j - 1) {
            int mid = i + (j - i) / 2;
            if (valid(nums, m, mid))
                j = mid;
            else
                i = mid+1;
        }
        return valid(nums, m, i) ? i : j;
    }
    bool valid(vector<int>& nums, int m, int _sum) {
        for (int cur_sum = 0, i = 0; i < nums.size(); i++) {
            if (nums[i] > _sum) return false;
            if (cur_sum + nums[i] > _sum) {
                cur_sum = 0;
                m--;
                if (m == 0) return false;
            }
            cur_sum += nums[i];
        }
        return true;
    }
};

 

以上是关于410. Split Array Largest Sum的主要内容,如果未能解决你的问题,请参考以下文章

410. Split Array Largest Sum

410. Split Array Largest Sum

410. Split Array Largest Sum

Split Array Largest Sum LT410

Leetcode 410. Split Array Largest Sum

leetcode 410. Split Array Largest Sum