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:
If n is the length of array, assume the following constraints are satisfied:

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ min(50, n)

Examples:

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.

思路:这种求最大值最小化的问题,就是BS的讨论,对最后可能的结果直接进行二分,然后判断是否可以到达mid,如此而已

public class Solution {
    public int splitArray(int[] nums, int m) {
        int max = Integer.MIN_VALUE, sum = 0;
        for(int i : nums)	{
        	sum += i;
        	max = Math.max(max, i);
        }
        
        // BS
        int lo = max, hi = sum;
        while(lo <= hi) {
        	int mid = lo + (hi - lo) / 2;
        	if(canGet(nums, mid, m))	lo = mid + 1;
        	else						hi = mid - 1;
        }
        
        return lo;
    }

	private boolean canGet(int[] nums, int mid, int m) {
		int cnt = 0, sum = 0;
		for(int i=0; i<nums.length; i++) {
			if(sum + nums[i] > mid) {
				cnt ++;
				if(cnt == m)	return true;
				sum = nums[i];
				continue;
			}
			
			sum += nums[i];
		}
		
		return false;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值