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