leetcode(410):Split Array Largest Sum

本文介绍了一种高效算法,用于解决将数组分割成m个连续子数组时,使得这些子数组各自和的最大值尽可能小的问题。通过二分查找法,避免了暴力解法的高时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【原题】
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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值