Copy Books

题目
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. )

答案

public class Solution {
    /**
     * @param pages: an array of integers
     * @param k: An integer
     * @return: an integer
     */
    public int copyBooks(int[] pages, int K) {
        int n = pages.length;

        // Minimal time to copy n books with k persons
        // f[i][k] = min{max{pages[j] + ... + pages[i - 1], f[j][k - 1]}}, j from 0 to i
        int[][] f = new int[n + 1][K + 1];
        int[] cumsum = new int[n];
        for(int i = 0; i < n; i++) {
            if(i == 0) cumsum[i] = pages[i];
            else cumsum[i] = cumsum[i - 1] + pages[i];
        }

        for(int i = 0; i <= n; i++) {
            for(int k = 1; k <= K; k++) {
                if(i == 0) {
                    f[i][k] = 0;
                    continue;
                }
                if(k == 1) {
                    f[i][k] = cumsum[i - 1];
                    continue;
                }
                int minval = Integer.MAX_VALUE, max, sum = 0;
                for(int j = i; j >= 0; j--) {
                    if(j > 0) sum = cumsum[i - 1] - cumsum[j - 1];
                    max = Math.max(f[j][k - 1], sum);
                    minval = Math.min(minval, max);
                }
                f[i][k] = minval;
            }
        }
        return f[n][K];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 先理发 等待化妆 涂口红 和妈妈 观看演出 上场了!从鞋上才能看出谁是你
    兰心儿阅读 275评论 0 1
  • 中豪珠宝爱情故事 岁月流转,冬去春将来。不曾记...
    曲颜修阅读 153评论 0 0
  • iphoneX适配方式: creator适配做的很好,以高,以宽作为适配,还是cocos2d-x以前那套,熟悉的味...
    工匠良辰阅读 2,619评论 0 0
  • 辞旧岁,迎新春,阔别2016期待2017的到来,这不是喜新厌旧,而是期待新气象。说起过年在儿时,那叫一个欢天...
    琴语言言阅读 198评论 1 1