Split Array Largest Sum——Difficulty:Hard

Problem :

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.

Example:

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

Output:
18

Explanation:
There are four ways to split nums into two subarrays.
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.

**

Algorithm:

**
在网上查到一种很巧妙地方法,用的二分查找。题目把一个数组分成连续的m个数组,得到这些数组求和后的最大值,我们要找的就是这个最大值中的最小值。
很容易知道,这个最大值的范围肯定是在
(原数组的最大值,原数组求和)这个范围内的。
所以就以这两个值为left和right进行二分查找,每次查找都是看对于当前这个mid值作为数组的最大值中的最小值,这个数组是否能满足分成m份的要求,如果能,就说明我们要得到的值还在mid的左边,如果不行,说明在mid右边。

时间复杂度:二分插值O( logn)*判断是否满足条件O(n)=O(nlogn)

**

Code:

class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        long long int left=0;
        long long int right=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>left)
                left=nums[i];
            right+=nums[i];
        }
        while(right>left)
        {
            long long int mid=(right+left)/2;
            if(check(nums,m,mid))
            {
                right=mid;
            }
            else
                left=mid+1;
        }
        return left;
    }
    bool check(vector<int>& nums,int m,int mid)
    {
        int c=1;
        int sum=0;
        for(int i=0;i<nums.size();i++)
        {
            sum+=nums[i];
            if(sum>mid)
            {
                sum=nums[i];
                c++;
                if(c>m)
                    return false;
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值