leetcode 410. Split Array Largest Sum

Posted exhausttolive

tags:

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

I saw something really interesting tonight…...

技术图片

So I tried this problem, but failed to figure out the O(n logn) algorithm

class Solution {
    public int splitArray(int[] nums, int m) {
        long l = 0, r = 0;
        int N = nums.length;
        for (int i = 0; i < N; ++i) {
            l = Math.max(nums[i],  l);
            r += nums[i];
        }
        while (l < r) {
            long mid = l + (r - l) / 2;
            if (match(nums, mid, m)) {
                r = mid;
            }
            else {
                l = mid + 1;
            }
        }
        return (int)l;
    }
    
    private boolean match(int[] nums, long threshold, int m) {
        long sum = 0;
        int j = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] + sum <= threshold) {
                sum += nums[i];
            }
            else {
                sum = nums[i];
                ++j;
            }
        }
        return j + 1 <= m;
    }
}

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

leetcode 410. Split Array Largest Sum

leetcode410 Split Array Largest Sum

410. Split Array Largest Sum

410. Split Array Largest Sum

410. Split Array Largest Sum

410. Split Array Largest Sum