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