Description

Given n books and each book has the same number of pages. There are k persons to copy these books and the i-th person needs times[i] minutes to copy a book.

Each person can copy any number of books and they start copying at the same time. What's the best strategy to assign books so that the job can be finished at the earliest time?

Return the shortest time.

Example

Example 1:

Input: n = 4, times = [3, 2, 4]
Output: 4
Explanation:
First person spends 3 minutes to copy 1 book.
Second person spends 4 minutes to copy 2 books.
Third person spends 4 minutes to copy 1 book.

Example 2:

Input: n = 4, times = [3, 2, 4, 5]
Output: 4
Explanation: Use the same strategy as example 1 and the forth person does nothing.
思路:

可以使用二分或者动态规划解决这道题目. 不过更推荐二分答案的写法, 它更节省空间, 思路简洁, 容易编码.

对于假定的时间上限 tm 我们可以使用贪心的思想判断这 k 个人能否完成复印 n 本书的任务: 每个人都在规定时间内尽可能多地复印, 判断他们复印的总数是否不小于 n 即可.

而时间上限 tm 与可否完成任务(0或1)这两个量之间具有单调性关系, 所以可以对 tm 进行二分查找, 查找最小的 tm, 使得任务可以完成.

public class Solution {
/**
* @param n: An integer
* @param times: an array of integers
* @return: an integer
*/
public int copyBooksII(int n, int[] times) {
if (n == 0) {
return 0;
}
int left = 0, right = times[0] * n;
while (left < right) {
int mid = left + (right - left) / 2;
if (check(n, times, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
} private boolean check(int n, int[] times, int limit) {
int count = 0;
for (int i : times) {
count += limit / i;
}
return count >= n;
}
}

  

05-17 02:55