跳转至

分割数组的最大值⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
private:
    bool check(vector<int>& nums, int k, int mid) {
        int sum = 0, cnt = 0;
        for (int x : nums) {
            if (x > mid) return false;
            if (sum + x > mid) {
                cnt++; sum = x;
            } else {
                sum += x;
            }
        }
        if (sum) cnt++;
        return cnt <= k;
    }

public:
    int splitArray(vector<int>& nums, int k) {
        // let l = -1 instead of l = 0 to past the test case: nums = [0]
        int l = -1, r = INT_MAX;
        while (l + 1 < r) {
            int mid = (long long)l + r >> 1;
            if (check(nums, k, mid)) r = mid;
            else l = mid;
        }
        return r;
    }
};