leetcode(410):Split Array Largest Sum

来源:互联网 发布:中控科门禁软件下载 编辑:程序博客网 时间:2024/05/21 22:20

【原题】
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.

Examples:

Input: nums = [7,2,5,10,8]
m = 2

Output: 18
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

【分析】
题意为给定一个非负整数的数组和正整数m,你能把原数组分割成m个连续的子数组,要求这些子数组各自的和的最大值的最小值。

举个例子:

输入数组[7,2,5,10,8]和m=2
即要求分割成两个子数组并且是连续的,则一共有4种分割法。
其中分割成[7,2,5]和[10,8]两个子数组时,能满足要求
比如分割成[7,2]和[5,10,8],子数组和的最大值为5+10+8=23>18
不满足要求。

若遍历每一种可能的分法然后取最大值的最小值,虽然能求得结果,但复杂度非常高,当数组很长时不可取。

这里分享一个别人的算法,点击链接

既然求最大值的最小值,可以想到二分查找。

初步可以分析出最后的结果一定大于数组里面的最大值,此时这个最大值单独成为一个数组,还可以分析出最后的结果一定小于等于原数组的和,此时原数组没有分割。

这时可以从两个端点进行二分查找,取两端点的中间值,然后检查这个中间值是否能将原数组分割成m个子数组,若能,再逐步缩小范围继续二分查找,如此迭代下去直到找到满足要求的解。

下面看Java实现的代码

【Java】

public class Solution {    public int splitArray(int[] nums, int m) {        long sum = 0;        int max = 0;        for (int num : nums) {            max = Math.max(max, num);            sum+=num;        }        if(m==1) return (int)sum;        long start = max,end = sum;        while(start<=end){            long mid = (start+end)/2;            if(valid(nums,mid,m)){                end =mid-1;            }else{                start = mid+1;            }        }        return (int)start;    }    private  boolean valid(int[] nums, long ret, int m) {        long tempSum = 0;        int count = 1;        for (int num : nums) {            tempSum+=num;            if(tempSum>ret){                tempSum=num;                count++;                if(count>m)                    return false;            }        }        return true;    }}
0 0