×

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We are going to distribute the books to every student. You have to find out the minimum value of pages given to the student who has to read a maximum number of pages.

To allocate the books, you have to follow some conditions, which are as follows:

  1. You have to allocate a minimum of one book to each student.
  2. You have to allocate the books from an array in a continuous way. If the array is [ 23, 50, 70, 95 ], then you can not give one student a book with 23 pages and a book with 95 pages. You have to give in a manner like 23, 50, 70.
  3. You have to allocate a particular book to only one student.

Let’s take an example:

Input- [10, 20, 30, 40, 50] and 2

Output-  90

Explanation- We can allocate the books in this ways-

  • First case: -
    • student1 : 10 ( total page = 10)
      • student2 : 20, 30, 40, 50 (total page = 140)
      • Max pages allocated : 140
    • Second case: -
      • student1 : 10, 20 ( total page = 30)
      • student2 : 30, 40, 50 (total page = 120)
      • Max pages allocated : 120
    • Third case: -
      • student1 : 10, 20, 30 ( total page = 60)
      • student2 : 40, 50 (total page = 90)
      • Max pages allocated : 90
    • Fourth case: -
      • student1 : 10, 20, 30, 40 ( total page = 100)
      • student2 : 50 (total page = 50)
      • Max pages allocated : 100

So we can see that in the third case, we get the minimum value of maximum pages allocated to a student. Our answer is 90.

Solution: - We shall use the binary search approach to solve this problem. Let’s see the algorithm.

Algorithm:-

Step 1: Start

Step 2: An array of size n is taken from the user. The number of students is also taken.

Step 3: After that, one function is called to implement a binary search.

Step 4: The function checks the minimum value in the range from zero to the sum of all elements in the array.

Step 5: We call another function to check whether the minimum value could be the answer or not.

Step 6: In this function, we check the number of students required to allocate all the books (maximum books allowed to a student should be the mid element of the range) is equal to the given student numbers or not.

Step 7: A variable is declared to store the minimum value. It updates itself when we find an appropriate value for books. After the ending of the while loop, we get the minimum value.

Step 8: The returned value will be printed.

Step 9: Stop.

Explanation of Algorithm: - In this algorithm, we use mainly two different functions. One function is used to implement binary search, and another is used to verify if the mid element is a proper value of maximum pages or not. For binary search, we use the range from the max element of the array to the sum of all elements in the array. We check the mid element by the second function. In this function, we calculate the minimum number of students required to distribute all the books among them (the condition is the maximum number of pages should not exceed the mid-value for one student). We store the mid-value in a variable and update it when the new mid-value satisfies the condition. After the ending of the loop, we get the answer.

Code: -

#include <bits/stdc++.h>
using namespace std;
 // function to check whether the minimum value could be the answer or not
bool isPossible(int array[], int n, int m, int min)
{
    int students = 1;
    int sum = 0;
    for (int i = 0; i < n; i++) {
        if (array[i] > min)
            return false;
        if (sum + array[i] > min) {
            students++;
            sum = array[i];
            if (students > m)
                return false;
        }
        else
            sum += array[i];
    }
    return true;
}
 
// function to find minimum pages using binary search
int findPages(int arr[], int n, int m)
{
    long long sum = 0;
    if (n < m)
        return -1;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    int start = 0, end = sum;
    int result = 0;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (isPossible(arr, n, m, mid)) {
            result = mid;
            end = mid - 1;
        }
 
        else
            start = mid + 1;
    }
 
    return result;
}
 
// Drivers code
int main()
{
    int arr [ 50 ];
    int n ;
cin >> n;
for(int i=0 ; i<n; i++){
cin>> arr[i];
}
    int m = 2; // No. of students
 
    cout << "Minimum number of pages = "
         << findPages(arr, n, m) << endl;
    return 0;
}

Input-

[ 10, 20, 30, 40, 50 ] and 2

Output- 

Minimum number of pages = 90

Input-

[ 10, 20, 30, 40 ] and 2

Output- 

Minimum number of pages = 60

Complexity Analysis: -

Time complexity- If N is the size of the array, max is the element of the array, and M is the sum of all the elements of the array then the complexity is O(N*log (M – max)).

Space complexity- Space complexity will be O(1).


Related Topics

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python Set issubset() method

Python Set issubset() method The set.issubset() method in Python returns True if all items in the set exists in the specified set, otherwise it returns False. Syntax set.issubset(set1) Parameter set- This parameter represents the set to check whether...

2 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.