代码改变世界

The Painter's Partition Problem Part II

2014-12-24 21:35  李涛的技术博客  阅读(360)  评论(0编辑  收藏  举报

(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 = 0; i < n; i++)
    {
        if (A[i] > max)
            max = A[i];
    }
    return max;
}

int getSum(int A[], int n)
{
        int total = 0;
        for (int i = 0; i < n; i++)
            total += A[i];
        return total;
}

int getRequiredPainters(int A[], int n, int maxLengthPainter)
{
    int total =0;
    int numPainters = 1;
    for (int i = 0; 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 <= 0 || k <= 0)
        return -1;

    int lo = getMax(A, n);
    int hi = getSum(A, n);

    while (lo < hi)
    {
        int mid = lo + (hi-lo)/2;
        int requiredPainters = getRequiredPainter(A, n, mid);
        if (requiredPainters <= k)
            hi = mid;
        else
            lo = mid+1;
    }
    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.