lintcode:Copy Books

504 篇文章 0 订阅
230 篇文章 0 订阅

Given an array A of integer with size of n( means n books and number of pages of each book) and k people to copy the book. You must distribute the continuous id books to one people to copy. (You can give book A[1],A[2] to one people, but you cannot give book A[1], A[3] to one people, because book A[1] and A[3] is not continuous.) Each person have can copy one page per minute. Return the number of smallest minutes need to copy all the books.

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

Challenge

Could you do this in O(n*k) time ?


class Solution {
public:
    /**
     * @param pages: a vector of integers
     * @param k: an integer
     * @return: an integer
     */

int copyBooks(vector<int> &pages, int k) {
    // write your code here
    if (pages.size() == 0 || k == 0)
        return 0;
        
    if (k > pages.size())
        k = pages.size();
    
    vector<vector<int>> dp(k, vector<int>(pages.size()));
    vector<int> auxPages(pages.size());

    auxPages[0] = pages[0]; //页面的累加和
    dp[0][0] = pages[0];
    for (int i=1; i<pages.size(); i++)
    {
        auxPages[i] = auxPages[i-1]+pages[i];
        dp[0][i] = auxPages[i];
    }
    
    //dp[i][j] i个人抄写书,抄到以j下标结尾的书时的最少耗时
    
    for (int i=1; i<k; i++)
    {
        for (int j=i; j<pages.size(); j++)
        {
            int targetValue = INT_MAX;
            for (int m=i; m<=j; m++)
            {
                //i-1人抄到下标为m-1的书,剩下的一人抄从m到j的书
                targetValue = min(max(dp[i-1][m-1], auxPages[j]-auxPages[m-1]), targetValue);
            }
            dp[i][j] = targetValue;
        }
    }
    
    return dp[k-1][pages.size()-1];
}

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值