LintCode 437:Copy books Java实现
Given n books and the ith book has A[i] pages. You are given k people to copy the n books.
n books list in a row and each person can claim a continous range of the n books. For example one copier can copy the books from ith to jth continously, but he can not copy the 1st book, 2nd book and 4th book (without 3rd book).
They start copying books at the same time and they all cost 1 minute to copy 1 page of a book. What’s the best strategy to assign books so that the slowest copier can finish at earliest time?
Example
Given array A = [3,2,4], k = 2.
Return 5( First person spends 5 minutes to copy book 1 and book 2 and second person spends 4 minutes to copy book 3. )
这一道题其实的概念就是算法导论中提到的“最大值最小化“ 的问题。
由于题目规定了说 一个抄写员只可以抄写连续的书(不可以抄1和3,只可以123)让我们想想一下当给定时间T内需要抄写完成books,需要多少个抄写员。这样我们就可以把不断的给出时间T看看是否能满足给定的抄写员数量,利用二分法就可以解决这个问题了。
让我们看看java的实现代码
class Copy{
public int copyBooks(int[] books,int people){
if(books == null || books.length == 0){
return 0;
}
int start = 0, end = 0;
for(int i = 0;i < books.length;i++){
start = Math.max(start,books[i];
end + = books[i];
}
while(start + 1 < end){
int mid = (end-start)/2 + start;
if(countPeople(books,mid)> k){
end = mid;
}else{
start = mid;
}
}
if(countPeople(books,start) < people){
return start;
}
return end;
}
private int countPeople(int[] books,int time){
int sum = 0;
int people = 1;
for(int i = 0; i < books.length;i++){
if(sum + books[i] > time){
people++;
sum = 0;
}
sum += books[i];
}
return people;
}
}
这样我们就可以完成这一道本质是最大值最小化的copybooks问题了。