The Wayback Machine - https://web.archive.org/web/20240930231816/https://www.geeksforgeeks.org/the-painters-partition-problem-using-binary-search/
Open In App

The Painter’s Partition Problem using Binary Search

Last Updated : 09 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Hard
27.52%
1.2L

Given are N boards of with length of each given in the form of array, and K painters, such that each painter takes 1 unit of time to paint 1 unit of the board. The task is to find the minimum time to paint all boards under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}.

Examples: 

Input: N = 4, A = {10, 10, 10, 10}, K = 2 

Output : 20

Explanation: Here we can divide the boards into 2 equal sized partitions (Painter 1 will paint boards A1 and A2, and Painter 2 will paint boards A3 and A4). So each painter gets 20 units of board and the total time taken is 20. 

Input: N = 4, A = {10, 20, 30, 40}, K = 2 

Output : 60

Explanation: Since there are only 2 painters, therefore divide first 3 boards to painter 1 (A1, A2 and A3) with time = 60, and last board to painter 2 (A4) with time = 40. Therefore total time taken = 60, which is the minimum possible.

Please note the combination A1 and A4 to Painter 1 with time 50, and A2 and A3 to Painter 2 with time 50, will yield a smaller time (50 units). But this cant be considered due to the constraint that a painter cannot paint non-continuos series of boards.

In the Painter’s Programming, we have discussed a dynamic programming based approach having time complexity of O(k∗N2) and O(k∗N) extra space. In this post we will look into a more efficient approach using binary search. 

Efficient Approach for Painter’s Problem using Binary Search

The idea to apply Binary Search Approach to Painter’s Problem is based on following observations:

We know that the invariant of binary search has three main parts: 

  • the target value would always be in the searching range. 
  • the searching range will decrease in each loop so that the termination can be reached. 
  • We also know that the values in this range must be in sorted order. 

Here our target value is the maximum sum of a contiguous section in the optimal allocation of boards. 

Now how can we apply binary search for this? 

We can fix the possible low to high range for the target value and narrow down our search to get the optimal allocation.

  • We can see that the highest possible value in this range is the sum of all the elements in the array and this happens when we allot 1 painter all the sections of the board. 
  • The lowest possible value of this range is the maximum value of the array max, as in this allocation we can allot max to one painter and divide the other sections such that the cost of them is less than or equal to max and as close as possible to max. 
  • Now if we use x painters in the above scenarios, it is obvious that as the value in the range increases, the value of x decreases and vice-versa. 

From this we can find the target value when x=k and use a helper function to find x, the minimum number of painters required when the maximum length of section a painter can paint is given.

C++




// CPP program for painter's partition problem
#include <climits>
#include <iostream>
using namespace std;
 
// return the maximum element from the array
int getMax(int arr[], int n)
{
    int max = INT_MIN;
    for (int i = 0; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}
 
// return the sum of the elements in the array
int getSum(int arr[], int n)
{
    int total = 0;
    for (int i = 0; i < n; i++)
        total += arr[i];
    return total;
}
 
// find minimum required painters for given maxlen
// which is the maximum length a painter can paint
int numberOfPainters(int arr[], int n, int maxLen)
{
    int total = 0, numPainters = 1;
 
    for (int i = 0; i < n; i++) {
        total += arr[i];
 
        if (total > maxLen) {
 
            // for next count
            total = arr[i];
            numPainters++;
        }
    }
 
    return numPainters;
}
 
int partition(int arr[], int n, int k)
{
    int lo = getMax(arr, n);
    int hi = getSum(arr, n);
 
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        int requiredPainters
            = numberOfPainters(arr, n, mid);
 
        // find better optimum in lower half
        // here mid is included because we
        // may not get anything better
        if (requiredPainters <= k)
            hi = mid;
 
        // find better optimum in upper half
        // here mid is excluded because it gives
        // required Painters > k, which is invalid
        else
            lo = mid + 1;
    }
 
    // required
    return lo;
}
 
// driver function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    cout << partition(arr, n, k) << endl;
    return 0;
}


Java




// Java Program for painter's partition problem
import java.io.*;
import java.util.*;
 
class GFG {
    // return the maximum element from the array
    static int getMax(int arr[], int n)
    {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++)
            if (arr[i] > max)
                max = arr[i];
        return max;
    }
 
    // return the sum of the elements in the array
    static int getSum(int arr[], int n)
    {
        int total = 0;
        for (int i = 0; i < n; i++)
            total += arr[i];
        return total;
    }
 
    // find minimum required painters for given maxlen
    // which is the maximum length a painter can paint
    static int numberOfPainters(int arr[], int n,
                                int maxLen)
    {
        int total = 0, numPainters = 1;
 
        for (int i = 0; i < n; i++) {
            total += arr[i];
 
            if (total > maxLen) {
 
                // for next count
                total = arr[i];
                numPainters++;
            }
        }
 
        return numPainters;
    }
 
    static int partition(int arr[], int n, int k)
    {
        int lo = getMax(arr, n);
        int hi = getSum(arr, n);
 
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            int requiredPainters
                = numberOfPainters(arr, n, mid);
 
            // find better optimum in lower half
            // here mid is included because we
            // may not get anything better
            if (requiredPainters <= k)
                hi = mid;
 
            // find better optimum in upper half
            // here mid is excluded because it gives
            // required Painters > k, which is invalid
            else
                lo = mid + 1;
        }
 
        // required
        return lo;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
        // Calculate size of array.
        int n = arr.length;
        int k = 3;
        System.out.println(partition(arr, n, k));
    }
}
 
// This code is contributed by Sahil_Bansall


Python3




# Python program for painter's partition problem
 
# Find minimum required painters for given maxlen
# which is the maximum length a painter can paint
 
 
def numberOfPainters(arr, n, maxLen):
    total = 0
    numPainters = 1
 
    for i in arr:
        total += i
 
        if (total > maxLen):
 
            # for next count
            total = i
            numPainters += 1
 
    return numPainters
 
 
def partition(arr, n, k):
    lo = max(arr)
    hi = sum(arr)
 
    while (lo < hi):
        mid = lo + (hi - lo) // 2
        requiredPainters = numberOfPainters(arr, n, mid)
 
        # find better optimum in lower half
        # here mid is included because we
        # may not get anything better
        if (requiredPainters <= k):
            hi = mid
 
        # find better optimum in upper half
        # here mid is excluded because it gives
        # required Painters > k, which is invalid
        else:
            lo = mid + 1
 
    # required
    return lo
 
 
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
k = 3
print(int(partition(arr, n, k)))


C#




// C# Program for painter's
// partition problem
using System;
 
class GFG {
 
    // return the maximum
    // element from the array
    static int getMax(int[] arr, int n)
    {
        int max = int.MinValue;
        for (int i = 0; i < n; i++)
            if (arr[i] > max)
                max = arr[i];
        return max;
    }
 
    // return the sum of the
    // elements in the array
    static int getSum(int[] arr, int n)
    {
        int total = 0;
        for (int i = 0; i < n; i++)
            total += arr[i];
        return total;
    }
 
    // find minimum required
    // painters for given
    // maxlen which is the
    // maximum length a painter
    // can paint
    static int numberOfPainters(int[] arr, int n,
                                int maxLen)
    {
        int total = 0, numPainters = 1;
 
        for (int i = 0; i < n; i++) {
            total += arr[i];
 
            if (total > maxLen) {
 
                // for next count
                total = arr[i];
                numPainters++;
            }
        }
 
        return numPainters;
    }
 
    static int partition(int[] arr, int n, int k)
    {
        int lo = getMax(arr, n);
        int hi = getSum(arr, n);
 
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            int requiredPainters
                = numberOfPainters(arr, n, mid);
 
            // find better optimum in lower
            // half here mid is included
            // because we may not get
            // anything better
            if (requiredPainters <= k)
                hi = mid;
 
            // find better optimum in upper
            // half here mid is excluded
            // because it gives required
            // Painters > k, which is invalid
            else
                lo = mid + 1;
        }
 
        // required
        return lo;
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
        // Calculate size of array.
        int n = arr.Length;
        int k = 3;
        Console.WriteLine(partition(arr, n, k));
    }
}
 
// This code is contributed by ajit


PHP




<?php
// PHP program for painter's
// partition problem
 
// return the maximum
// element from the array
function getMax($arr, $n)
{
    $max = PHP_INT_MIN;
    for ($i = 0; $i < $n; $i++)
        if ($arr[$i] > $max)
            $max = $arr[$i];
    return $max;
}
 
// return the sum of the
// elements in the array
function getSum($arr, $n)
{
    $total = 0;
    for ($i = 0; $i < $n; $i++)
        $total += $arr[$i];
    return $total;
}
 
// find minimum required painters
// for given maxlen which is the
// maximum length a painter can paint
function numberOfPainters($arr, $n,
                          $maxLen)
{
    $total = 0; $numPainters = 1;
 
    for ($i = 0; $i < $n; $i++)
    {
        $total += $arr[$i];
 
        if ($total > $maxLen)
        {
 
            // for next count
            $total = $arr[$i];
            $numPainters++;
        }
    }
 
    return $numPainters;
}
 
function partition($arr, $n, $k)
{
    $lo = getMax($arr, $n);
    $hi = getSum($arr, $n);
 
    while ($lo < $hi)
    {
        $mid = $lo + ($hi - $lo) / 2;
        $requiredPainters =
                    numberOfPainters($arr,
                                     $n, $mid);
 
        // find better optimum in
        // lower half here mid is
        // included because we may
        // not get anything better
        if ($requiredPainters <= $k)
            $hi = $mid;
 
        // find better optimum in
        // upper half here mid is
        // excluded because it
        // gives required Painters > k,
        // which is invalid
        else
            $lo = $mid + 1;
    }
 
    // required
    return floor($lo);
}
 
// Driver Code
$arr = array(1, 2, 3,
             4, 5, 6,
             7, 8, 9);
$n = sizeof($arr);
$k = 3;
 
echo partition($arr, $n, $k), "\n";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// Javascript Program for painter's partition problem
    
// Return the maximum element from the array
function getMax(arr, n)
{
    let max = Number.MIN_VALUE;
    for(let i = 0; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
             
    return max;
}
 
// Return the sum of the elements in the array
function getSum(arr, n)
{
    let total = 0;
    for(let i = 0; i < n; i++)
        total += arr[i];
         
    return total;
}
 
// Find minimum required paleters for given maxlen
// which is the maximum length a paleter can palet
function numberOfPaleters(arr, n, maxLen)
{
    let total = 0, numPaleters = 1;
 
    for(let i = 0; i < n; i++)
    {
        total += arr[i];
 
        if (total > maxLen)
        {
 
            // For next count
            total = arr[i];
            numPaleters++;
        }
    }
    return numPaleters;
}
 
function partition(arr, n, k)
{
    let lo = getMax(arr, n);
    let hi = getSum(arr, n);
 
    while (lo < hi)
    {
        let mid = lo + (hi - lo) / 2;
        let requiredPaleters = numberOfPaleters(
            arr, n, mid);
 
        // Find better optimum in lower half
        // here mid is included because we
        // may not get anything better
        if (requiredPaleters <= k)
            hi = mid;
 
        // find better optimum in upper half
        // here mid is excluded because it gives
        // required Paleters > k, which is invalid
        else
            lo = mid + 1;
    }
 
    // Required
    return lo;
}
 
// Driver code
let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
 
// Calculate size of array.
let n = arr.length;
let k = 3;
 
document.write(Math.round(partition(arr, n, k)));
 
// This code is contributed by sanjoy_62
 
</script>


Output

17

Time Complexity: O(N*log(sum(arr[])))

Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

The Painter's Partition Problem
Given are N boards of with length of each given in the form of array, and K painters, such that each painter takes 1 unit of time to paint 1 unit of the board. The task is to find the minimum time to paint all boards under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothin
15+ min read
Painter's Algorithm in Computer Graphics
Painter's algorithm is the algorithm which is introduced by Hewells  in 1972. The techniques used by these algorithms are image space and object space. The name of this algorithm is Painter's because it's working is like a painter who creating an oil painting. Just like an artist paints, he start his painting with an empty canvas, the first thing t
4 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Minimum cost to partition the given binary string
Given a binary string str and an integer K, the task is to find the minimum cost required to partition the string into exactly K segments when the cost of each segment is the product of the number of set bits with the number of unset bits and total cost is sum of cost of all the individual segments.Examples: Input: str = "110101", K = 3 Output: 2 1
10 min read
Count ways to partition a Binary String such that each substring contains exactly two 0s
Given binary string str, the task is to find the count of ways to partition the string such that each partitioned substring contains exactly two 0s. Examples: Input: str = "00100" Output: 2Explanation: Possible ways to partition the string such that each partition contains exactly two 0s are: { {"00", "100"}, {"001", "00"} }. Therefore, the require
6 min read
Count ways to partition Binary Array into subarrays containing K 0s each
Given a binary array arr[] of size N, and an integer K, the task is to calculate the number of ways to partition the array into non-overlapping subarrays, where each subarray has exactly K number 0s. Examples: Input: arr[] = [ 0, 0, 1, 1, 0, 1, 0], K = 2Output: 3Explanation: Different possible partitions are: {{0, 0}, {1, 1, 0, 1, 0}}, {{0, 0, 1},
8 min read
Find minimum number of non palindromic partition of Binary Array
Given a binary array A[] of length 2*N, the task is to find the minimum number of partitions that follow the below conditions: Each array element belongs to exactly one partitionNone of the partitioned subarrays is a palindrome Note: If there are multiple answers print anyone that satisfies the above conditions and if no such partition exists that
7 min read
Minimum toggles to partition a binary array so that it has first 0s then 1s
Given an array of n integers containing only 0 and 1. Find the minimum toggles (switch from 0 to 1 or vice-versa) required such the array become partitioned, i.e., it has first 0s than 1s. There should be at least one 0 in the beginning, and there can be zero or more 1s in the end. Input: arr[] = {1, 0, 1, 1, 0} Output: 2 Toggle the first and last
7 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Implementing Water Supply Problem using Breadth First Search
Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through
10 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read