欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode_每日一题今日份_410.分割数组的最大值

程序员文章站 2022-03-16 11:22:51
...

LeetCode_每日一题今日份_410.分割数组的最大值

LeetCode_每日一题今日份_410.分割数组的最大值

bool check(int* nums, int numsSize, int m, int x) {
    long long sum = 0; //当前分割子数组的和
    int cnt = 1; //已经分割出的子数组的数量(包括当前子数组)
    for (int i = 0; i < numsSize; i++) {
        if (sum + nums[i] > x) {
            cnt++;
            sum = nums[i];
        } else {
            sum += nums[i];
        }
    }
    return cnt <= m;
}

int splitArray(int* nums, int numsSize, int m) {
    long long left = 0, right = 0;
    for (int i = 0; i < numsSize; i++) {
        right += nums[i];
        if (left < nums[i]) {
            left = nums[i];
        }
    }
    while (left < right) {
        long long mid = (left + right) >> 1;
        if (check(nums, numsSize, m, mid)) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return left;
}