Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.
FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.
FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.
Input
Line 1: Two space-separated integers: N and M
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Line 1: The smallest possible monthly limit Farmer John can afford to live with.
Sample Input
7 5
100
400
300
100
500
101
400
Sample Output
500
Hint
If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.
题意:n个数的序列,分成m组(序列连续),得到m个序列和,m个和中有一个最大值,是这个最大值最小化
思路:对序列二分,下限是序列的最大值,上限是序列的和,判断条件check()函数--把序列最小分组数量与m比较,如果最小的分组数量都比m大,说明这个mid不可取
注意的一点:因为是求mid最小值,mid满足条件时,r=mid-1;不满足时,l=mid+1
代码:
import java.util.Scanner;
public class Main {
static int n,m;
static int max=100005;
static int a[]=new int[max];
public static boolean check(int mid){
int res=1,sum=0;
for(int i=0;i<n;i++){
sum+=a[i];
if(sum>=mid){
res++;
if(sum==mid) sum=0;//当前花费计入当前组
else sum=a[i];//当前花费计入下一组
if(n-1==i) res--;//当前月被计入最后一个分组
}
}
if(res>m) return false;
else return true;
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
n=scan.nextInt();
m=scan.nextInt();
int sum=0,max=0;
for(int i=0;i<n;i++){
a[i]=scan.nextInt();
sum+=a[i];
max=Math.max(a[i], max);
}
int l=max,r=sum,mid=0,ans=0;
while(l<=r){
mid=(l+r)/2;
if(check(mid)){
r=mid-1;
ans=mid;
}
else{
l=mid+1;
}
}
System.out.println(ans);
}
}