leetcode 410. Split Array Largest Sum

I saw something really interesting tonight…...

73421555080080_.pic

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;
    }
}
posted on 2019-04-12 23:32  王 帅  阅读(108)  评论(0编辑  收藏  举报