LintCode "Copy Books"

Classic DP. The initial intuitive O(k*n^2) solution is like this:

class Solution {
public:
    /**
     * @param pages: a vector of integers
     * @param k: an integer
     * @return: an integer
     */
    int copyBooks(vector<int> &pages, int k) {
        size_t n = pages.size();
        if(k > n)
        {
            return *max_element(pages.begin(), pages.end());
        }

        //    Prefix Sums
        vector<long long> psum(n);
        for(int i = 0; i < n; i ++)
            psum[i] = i == 0? pages[i] : (psum[i - 1] + pages[i]);

        //  DP
        vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, INT_MAX));
        for(int i = 1; i <= n; i ++)
            dp[i][1] = psum[i - 1];

        for(int i = 2; i <= k; i ++) // person
        for(int b = i; b <= n; b ++) // book
        for(int c = i-1; c < b; c ++) // prev book
        {
            long long last = dp[c][i - 1];
            long long cur  = psum[b-1] - psum[c - 1];
            dp[b][i] = min(dp[b][i], max(cur, last));
        }

        return dp[n][k];
    }
};

O(nk): http://sidbai.github.io/2015/07/25/Copy-Books/
Point above: 

long long last = dp[c][i - 1];
long long cur  = psum[b-1] - psum[c - 1];
min(dp[b][i], max(cur, last));

dp[c][i-1] is mono-inc by c, cur is mono-dec. min(.., max(cur,last)) is V-like in 2D plane. So we can use 2-pointers to find the bottom of the V!

Or, binary search with O(nlg(sum/k)): https://github.com/kamyu104/LintCode/blob/master/C++/copy-books.cpp

转载于:https://www.cnblogs.com/tonix/p/4858737.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值