Leetcode410. Split Array Largest Sum

Posted wuezs

tags:

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

题目链接: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只做出来这三题。



算法:

   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;
    


以上是关于Leetcode410. 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