题目链接:https://leetcode.com/contest/7/problems/split-array-largest-sum/]


补充链接:https://leetcode.com/problems/split-array-largest-sum


contest所有题目最后都会出现在problems上


题目:

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.

Write an algorithm to minimize the largest sum among these m subarrays.Note:Given m satisfies the following constraint: 1 ≤ m ≤ length(nums) ≤ 14,000.


思路:

先计算subarrays sum的上下界,在该范围内二分法搜索满足条件的sum(以该sum贪心划分array 看能否满足sum>=所有subarray的sum)。并记录最小的sum。


本次contest只做出来这三题。

【Leetcode】410. Split Array Largest Sum_i++


算法:

public int splitArray(int[] nums, int m) {
        int high = 0, low = 0, mid = 0, ans = 0;
        for (int num : nums) {
            high += num;
            low = Math.max(num, low);
        }

        if (m == 1)
            return high;
        if (m == nums.length)
            return low;
        ans = high;
        while (low <= high) {
            mid = low + (high - low) / 2;

            boolean flag = true;
            int sum = nums[0];
            int count = 1;
            for (int i = 1; i < nums.length; i++) {
                sum += nums[i];
                if (sum > mid) {
                    count++;
                    sum = nums[i];
                }
                if (count > m) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                high = mid - 1;
                ans = mid;
            } else {
                low = mid + 1;
            }
        }
        return ans;
    }