美文网首页
Copy Books

Copy Books

作者: BLUE_fdf9 | 来源:发表于2018-10-24 03:59 被阅读0次

题目
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];
    }
}

相关文章

  • Copy Books

    题目Given n books and the ith book has A[i] pages. You are ...

  • Copy Books - Binary Search

    Question from lintcodeGiven n books and the ith book has ...

  • Copy Books II - dynamic programm

    Question from lintcodeGiven n books( the page number of e...

  • Lintcode437 Copy Books solution

    【题目描述】 Givennbooks and theith book hasA[i]pages. You are ...

  • Copy Books II - non-optimized ve

    Question from lintcodeGiven n books( the page number of e...

  • Reader Takes All

    寫在最前面—— Passion of the books, by the books, for the books...

  • Books

    一 JS书籍推荐JS高级程序设计 (望远镜)JS工作原理犀牛书二、行业书籍《人月神话》

  • books

    在手机里存在的,已看完的书单

  • BOOKS

    书籍 除了百科全书中提供的书目和您在阅读的文章中提到的那些书目之外,您还可以查阅图书馆的卡片或电脑目录,这是书架上...

  • Books

    这里有两只在书店一看到书就两眼发青光的家伙~~~真希望我的外甥女小羽绮长大后也能像你一样爱看书呢~~~

网友评论

      本文标题:Copy Books

      本文链接:https://www.haomeiwen.com/subject/dhazzftx.html