Copy Books

Given n books and the i-th book has pages[i] pages. There are k persons to copy these books.

These books list in a row and each person can claim a continous range of books. For example, one copier can copy the books from i-th to j-th 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?

Return the shortest time that the slowest copier spends.

Example

Example 1:

Input: pages = [3, 2, 4], k = 2
Output: 5
Explanation: 
    First person spends 5 minutes to copy book 1 and book 2.
    Second person spends 4 minutes to copy book 3.

Example 2:

Input: pages = [3, 2, 4], k = 3
Output: 4
Explanation: Each person copies one of the books.

Challenge

O(nk) time

Notice

The sum of book pages is less than or equal to 2147483647

思路:二分答案,直接求不好求,那么我们就问,如果给你无穷多的人,你需要多久? Max(Length of page[i]), 如果给你1个人,你需要多久,sum (Pages[i]) ,那么问题来了,你需要求给你k个人情况下的,你需要多久。很显然,这又是个递增递减的关系;

人越多,需要的时间越少,人越少需要的时间越多;

create一个canCopy函数,看在K个人的情况下,limit time能否copy完,那么搜索能够用k个人copy完的最小的时间。

public class Solution {
    /**
     * @param pages: an array of integers
     * @param k: An integer
     * @return: an integer
     */
    public int copyBooks(int[] pages, int k) {
        if(pages == null || pages.length == 0) {
            return 0;
        }
        int start = 0; // max(p)
        int end = 0; // sum(p)
        for(int p: pages) {
            start = Math.max(start, p);
            end += p;
        }

        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(needPerson(mid, pages) > k) {
                start = mid;
            } else {
                // needPerson(mid, pages) <= k
                end = mid;
            }
        }
        if(needPerson(start, pages) > k) { // 这个判断条件,跟上面的判断start, end一模一样;
            return end;
        }
        return start;
    }

    private int needPerson(int timelimit, int[] pages) {
        int count = 0;
        int sum = 0;
        int i = 0;
        while(i < pages.length) {
            // 为了计算在时间limit下,一个人能够抄多少,最后计算出需要多少人在限定时间下能够抄完;
            while(i < pages.length && sum + pages[i] <= timelimit) {
                sum += pages[i];
                i++;
            }
            count++;
            sum = 0;
        }
        return count;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值