最大值最小问题,二分答案+Java代码实现

题意简述:长度为n的数组,分成k段,每段的和最大值最小是多少

解题关键:
首先,解一定存在,最大解就是数组的所有元素之和。
其次,如果数组进行划分后,每段之和都不超过m,划分为了t段,那一定可以划分为t-1段。所以我们只需要二分查找能否划分为不超过k段即可,当小于等于k段后,一定可以扩展为k段(因为只需要将某几段拆开就好了)

题目描述
You are given n packages of wi kg from a belt conveyor in order (i=0,1,…n−1). You should load all packages onto k trucks which have the common maximum load PP. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load P. Write a program which reads n, k and wi, and reports the minimum value of the maximum load PP to load all packages from the belt conveyor.
输入
In the first line, two integers n and k are given separated by a space character. In the following n lines, wi are given respectively.
输出
Print the minimum value of P in a line.
样例输入
5 3
8
1
7
3
9
样例输出
10
提示
1≤ n≤ 100,000
1≤ k≤ 100,000

Java代码实现

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int k = cin.nextInt();
        int[]a = new int[n];
        int left = 0, right = 0;
        for (int i = 0; i < n; i++){
            a[i] = cin.nextInt();
            left = Math.max(left, a[i]);
            right += a[i];
        }
        int mid;
        while(left < right){
            mid = (left + right) >> 1;
// System.err.println("left="+left+",right="+right+",mid="+mid);
            int t = 1, sum = a[0];
            for(int i = 1; i < n; i++){
                if(sum + a[i] <= mid){
                    sum += a[i];
                }else{
                    t++;
                    if(t > k)break;
                    sum = a[i];
                }
            }
// System.err.println("t="+t);
            if(t > k){//mid不是解
                left = mid + 1;
            }else{//mid是解
                right = mid;
            }
        }
        System.out.println(right);
    }

}
/* 4 2 1 2 2 6 */
点赞