当前位置: 首页 > 工具软件 > iCopy > 使用案例 >

Copy Books

壤驷英叡
2023-12-01

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;
    }
}

 类似资料:

相关阅读

相关文章

相关问答