Leetcode 410. Split Array Largest Sum 划分数组 解题报告

1 解题思想

首先声明下,本文这些内容,基本是dicuss的来的

题目意思是,给一个数组,需要划分成m份,让你找出一种划分方式,使得划分成m份后,最大的那一个区间的数值最小

这道题discuss上说的是2分查找,我也确实想不到更好的方式:
1、首先这个区间的值肯定是在[最大的单个数,所有数组只和] 中间的
2、利用二分查找的思想进行查找,查找范围和1的标注那个一样,必须要那个
3、查找时用valid验证,对于当前这个值,能否合法的划分出来?是多了还是少了,所谓的不合法就是说对于给定值,必须要划分了多余m个区间,才能让给定值是所有划分区间里最大值小于等于给定值

2 原题

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 = [1,2,3,4,5]
m = 2

Output:
9

Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [1,2,3] and [4,5],
where the largest sum among the two subarrays is only 9.

3 AC解

来自discuss
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;
        }
        return (int)binarySearch(nums, m, sum, max);
    }
    //二分查找
    private long binarySearch(int[] nums, int m, long high, long low){
        long mid = 0;
        while(low < high){
            mid = (high + low)/2;
            //验证是否满足,也就是这么大的值有可能出现么
            if(valid(nums, m, mid)){
                high = mid;
            }else{
                low = mid + 1;
            }
        }
        return high;
    }

    /**
     * 验证这个值是否合法
     * */
    private boolean valid(int[] nums, int m, long max){
        int cur = 0;
        int count = 1;
        //是否有多余m个片段or区间,大于给定值的max的,如果有了,那么就不合法了,因为这样划分就不止m个,及max太小
        for(int num: nums){
            cur += num;
            if(cur > max){
                cur = num;
                count++;
                if(count > m){
                    return false;
                }
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值