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

你可能感兴趣的:(Copy Books)