The Painter's Partition Problem Part II

时间:2023-03-10 02:34:09
The Painter's Partition Problem Part II

(http://leetcode.com/2011/04/the-painters-partition-problem-part-ii.html)

This is Part II of the artical: The Painter's Partition Problem. Please read Part I for more background information.

Solution:

Assume that you are assigning continuous section of board to each painter such that its total length must not exceed a predefined maximum, costmax. Then, you are able to find the number of painters that is required, x. Following are some key obervations:

  • The lowest possible value for costmax must be the maximum element in A (name this as lo).
  • The highest possible value for costmax must be the entire sum of A (name this as hi).
  • As costmax increases, x decreases. The opposite also holds true.

Now, the question translates directly into:

  • How do we use binary search to find the minimum of costmax while satifying the condition x=k? The search space will be the range of [lo, hi].
int getMax(int A[], int n)
{
int max = INT_MIN;
for (int i = ; i < n; i++)
{
if (A[i] > max)
max = A[i];
}
return max;
} int getSum(int A[], int n)
{
int total = ;
for (int i = ; i < n; i++)
total += A[i];
return total;
} int getRequiredPainters(int A[], int n, int maxLengthPainter)
{
int total =;
int numPainters = ;
for (int i = ; i < n; i++)
{
total += A[i];
if (total > maxLengthPerPainter)
{
total = A[i];
numPainters++;
}
}
return numPainters;
} int partition(int A[], int n, int k)
{
if (A == NULL || n <= || k <= )
return -; int lo = getMax(A, n);
int hi = getSum(A, n); while (lo < hi)
{
int mid = lo + (hi-lo)/;
int requiredPainters = getRequiredPainter(A, n, mid);
if (requiredPainters <= k)
hi = mid;
else
lo = mid+;
}
return lo;
}

The complexity of this algorithm is O(N log(∑Ai)), which is quite efficient. Furthermore, it does not require any extra space, unlike the DP solution which requires O(kN) space.