码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 410. Split Array Largest Sum

时间:2019-04-13 01:17:30      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:The   ...   class   bool   really   jpg   solution   pre   http   

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

标签:The   ...   class   bool   really   jpg   solution   pre   http   

原文地址:https://www.cnblogs.com/exhausttolive/p/10699313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!