LintCode 437:Copy books Java实现

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问题了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值