410. Split Array Largest Sum

can refer this:

https://leetcode.com/problems/split-array-largest-sum/discuss/161143/Logical-Thinking-with-Code-Beats-99.89

T : O(nlogn), n: range [max of nums , sum of nums]

S: O(1)

class Solution {
    public int splitArray(int[] nums, int m) {
        long max = 0;
        long sum = 0;
        for (int num : nums) {
            max = Math.max(max, num);
            sum += num;
        }
        
        long left = max;
        long right = sum;
        
        while (left < right) {
            long mid = left + (right - left)/2;
            
            if (splitOk(nums, m, mid)) {
                right = mid;    
            } else {
                left = mid+1;
            }
        }
        return (int)left;
    }
    private boolean splitOk(int[] nums, int m, long val) {
        long sum = 0;
        int count = 1; // 一開始就是一組
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (sum > val) { // 加太多, 超過時
                sum = nums[i]; // 往回退的意思
                count++;
                if (count > m) {
                    return false;
                }
            }
        }
        return true;
    }
}

left + 1 < right style

DP

T: O(mnk)

S: O(mn)

Last updated

Was this helpful?