The Wayback Machine - https://web.archive.org/web/20240917212844/https://www.geeksforgeeks.org/allocate-minimum-number-pages/
Open In App

Allocate Minimum Number of Pages from N books to M students

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given that there are N books and M students. Also given are the number of pages in each book in ascending order. The task is to assign books in such a way that the maximum number of pages assigned to a student is minimum, with the condition that every student is assigned to read some consecutive books. Print that minimum number of pages.

Examples: 

Input: N = 4, pages[] = {12, 34, 67, 90}, M = 2
Output: 113
Explanation: There are 2 students. Books can be distributed in following combinations:

  • {12} and {34, 67, 90} -> Max number of pages is allocated to student 2 with 34 + 67 + 90 = 191 pages
  • {12, 34} and {67, 90} -> Max number of pages is allocated to student 2 with 67 + 90 = 157
  • {12, 34, 67} and {90} -> Max number of pages is allocated to student 1 with 12 + 34 + 67 = 113 pages

The third combination has the minimum pages assigned to a student = 113.

Input: N = 3, pages[] = {15, 17, 20}, M = 2
Output: 32
Explanation: There are 2 students. Books can be distributed in following combinations:

  • {15} and {17, 20} -> Max number of pages is allocated to student 2 with 17 + 20 = 37 pages
  • {15, 17} and {20} -> Max number of pages is allocated to student 1 with 15 + 17 = 32 pages

The second combination has the minimum pages assigned to a student = 32.

Approaches to Allocate Minimum Number of Pages:

[Naive Approach] Generating all the permutations – O(N*N!) Time and O(N) Space:

The simplest approach to solve this problem is to find all permutations to distribute N books among M students, and return the minimum page allocation among them.

[Expected Approach] Using Binary Search – O(N * logN) Time and O(1) Space:

Another way to solve this problem is to use Binary Search, based on this idea:

Case 1: When no valid answer exists.

  • If the number of students is greater than the number of books (i.e, M > N), In this case at least 1 student will be left to which no book has been assigned.

Case 2: When a valid answer exists.

  • The maximum possible answer could be when there is only one student. So, all the book will be assigned to him and the result would be the sum of pages of all the books.
  • The minimum possible answer could be when number of student is equal to the number of book (i.e, M == N) , In this case all the students will get at most one book. So, the result would be the maximum number of pages among them (i.e, maximum(pages[])).
  • Hence, we can apply binary search in this given range and each time we can consider the mid value as the maximum limit of pages one can get. And check for the limit if answer is valid then update the limit accordingly.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Utility function to check if current minimum value
// is feasible or not.
bool isPossible(int arr[], int n, int m, int curr_min)
{
    int studentsRequired = 1;
    int curr_sum = 0;

    // iterate over all books
    for (int i = 0; i < n; i++) {
        // check if current number of pages are greater
        // than curr_min that means we will get the result
        // after mid no. of pages
        if (arr[i] > curr_min)
            return false;

        // count how many students are required
        // to distribute curr_min pages
        if (curr_sum + arr[i] > curr_min) {
            // increment student count
            studentsRequired++;

            // update curr_sum
            curr_sum = arr[i];

            // if students required becomes greater
            // than given no. of students,return false
            if (studentsRequired > m)
                return false;
        }

        // else update curr_sum
        else
            curr_sum += arr[i];
    }
    return true;
}

// function to find minimum pages
int findPages(int arr[], int n, int m)
{
    long long sum = 0;

    // return -1 if no. of books is less than
    // no. of students
    if (n < m)
        return -1;
    int mx = INT_MIN;

    // Count total number of pages
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        mx = max(mx, arr[i]);
    }

    // initialize start as 0 pages and end as
    // total pages
    int start = mx, end = sum;
    int result = INT_MAX;

    // traverse until start <= end
    while (start <= end) {
        // check if it is possible to distribute
        // books by using mid as current minimum
        int mid = (start + end) / 2;
        if (isPossible(arr, n, m, mid)) {
            // update result to current distribution
            // as it's the best we have found till now.
            result = mid;

            // as we are finding minimum and books
            // are sorted so reduce end = mid -1
            // that means
            end = mid - 1;
        }

        else
            // if not possible means pages should be
            // increased so update start = mid + 1
            start = mid + 1;
    }

    // at-last return minimum no. of  pages
    return result;
}

// Driver code
int main()
{
    // Number of pages in books
    int arr[] = { 12, 34, 67, 90 };
    int n = sizeof arr / sizeof arr[0];
    int m = 2; // No. of students

    cout << "Minimum number of pages = "
         << findPages(arr, n, m) << endl;
    return 0;
}
C
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Utility function to check if current minimum value
// is feasible or not.
bool isPossible(int arr[], int n, int m, int curr_min)
{
    int studentsRequired = 1;
    int curr_sum = 0;

    // iterate over all books
    for (int i = 0; i < n; i++) {
        // check if current number of pages are greater
        // than curr_min that means we will get the result
        // after mid no. of pages
        if (arr[i] > curr_min)
            return false;

        // count how many students are required
        // to distribute curr_min pages
        if (curr_sum + arr[i] > curr_min) {
            // increment student count
            studentsRequired++;

            // update curr_sum
            curr_sum = arr[i];

            // if students required becomes greater
            // than given no. of students,return false
            if (studentsRequired > m)
                return false;
        }

        // else update curr_sum
        else
            curr_sum += arr[i];
    }
    return true;
}

// function to find minimum pages
int findPages(int arr[], int n, int m)
{
    long long sum = 0;

    // return -1 if no. of books is less than
    // no. of students
    if (n < m)
        return -1;
    int mx = arr[0];

    // Count total number of pages
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        mx = (arr[i] > mx ? arr[i] : mx);
    }

    // initialize start as 0 pages and end as
    // total pages
    int start = mx, end = sum;
    int result = INT_MAX;

    // traverse until start <= end
    while (start <= end) {
        // check if it is possible to distribute
        // books by using mid as current minimum
        int mid = (start + end) / 2;
        if (isPossible(arr, n, m, mid)) {
            // update result to current distribution
            // as it's the best we have found till now.
            result = mid;

            // as we are finding minimum and books
            // are sorted so reduce end = mid -1
            // that means
            end = mid - 1;
        }

        else
            // if not possible means pages should be
            // increased so update start = mid + 1
            start = mid + 1;
    }

    // at-last return minimum no. of  pages
    return result;
}

// Driver code
int main()
{
    // Number of pages in books
    int arr[] = { 12, 34, 67, 90 };
    int n = sizeof arr / sizeof arr[0];
    int m = 2; // No. of students

    printf("Minimum number of pages = %d\n",
           findPages(arr, n, m));
    return 0;
}
Java
public class GFG {
    // Utility method to check if current minimum value
    // is feasible or not.
    static boolean isPossible(int arr[], int n, int m,
                              int curr_min)
    {
        int studentsRequired = 1;
        int curr_sum = 0;

        // iterate over all books
        for (int i = 0; i < n; i++) {
            curr_sum += arr[i];
            if (curr_sum > curr_min) {
                studentsRequired++; // increment student
                                    // count

                curr_sum = arr[i]; // update curr_sum
            }
        }

        return studentsRequired <= m;
    }

    // method to find minimum pages
    static int findPages(int arr[], int n, int m)
    {
        int sum = 0;

        // return -1 if no. of books is less than
        // no. of students
        if (n < m)
            return -1;
        int mx = arr[0];

        // Count total number of pages
        for (int i = 0; i < n; i++) {
            sum += arr[i];
            mx = (arr[i] > mx ? arr[i] : mx);
        }

        // initialize start as arr[n-1] pages(minimum answer
        // possible) and end as total pages(maximum answer
        // possible)
        int start = arr[n - 1], end = sum;
        int result = Integer.MAX_VALUE;

        // traverse until start <= end
        while (start <= end) {
            // check if it is possible to distribute
            // books by using mid is current minimum
            int mid = start + (end - start) / 2;
            if (isPossible(arr, n, m, mid)) {
                // update result to current distribution
                // as it's the best we have found till now.
                result = mid;

                // as we are finding minimum so,
                end = mid - 1;
            }

            else
                // if not possible, means pages should be
                // increased ,so update start = mid + 1
                start = mid + 1;
        }

        // at-last return minimum no. of  pages
        return result;
    }

    // Driver Method
    public static void main(String[] args)
    {

        int arr[] = { 12, 34, 67,
                      90 }; // Number of pages in books

        int m = 2; // No. of students

        System.out.println("Minimum number of pages = "
                           + findPages(arr, arr.length, m));
    }
}
Python
# Utility function to check if
# current minimum value is feasible or not.


def isPossible(arr, n, m, curr_min):
    studentsRequired = 1
    curr_sum = 0

    # iterate over all books
    for i in range(n):

        # check if current number of pages are
        # greater than curr_min that means
        # we will get the result after
        # mid no. of pages
        if (arr[i] > curr_min):
            return False

        # count how many students are required
        # to distribute curr_min pages
        if (curr_sum + arr[i] > curr_min):

            # increment student count
            studentsRequired += 1

            # update curr_sum
            curr_sum = arr[i]

            # if students required becomes greater
            # than given no. of students, return False
            if (studentsRequired > m):
                return False

        # else update curr_sum
        else:
            curr_sum += arr[i]

    return True

# function to find minimum pages


def findPages(arr, n, m):

    sum = 0

    # return -1 if no. of books is
    # less than no. of students
    if (n < m):
        return -1

    # Count total number of pages
    for i in range(n):
        sum += arr[i]

    # initialize start as 0 pages and
    # end as total pages
    start, end = 0, sum
    result = 10**9

    # traverse until start <= end
    while (start <= end):

        # check if it is possible to distribute
        # books by using mid as current minimum
        mid = (start + end) // 2
        if (isPossible(arr, n, m, mid)):

            # update result to current distribution
              # as it's the best we have found till now.
            result = mid

            # as we are finding minimum and books
            # are sorted so reduce end = mid -1
            # that means
            end = mid - 1

        else:
            # if not possible means pages should be
            # increased so update start = mid + 1
            start = mid + 1

    # at-last return minimum no. of pages
    return result

# Driver Code


# Number of pages in books
arr = [12, 34, 67, 90]
n = len(arr)
m = 2   # No. of students

print("Minimum number of pages = ",
      findPages(arr, n, m))
C#
using System;

class GFG {

    // Utility function to check
    // if current minimum value
    // is feasible or not.
    static bool isPossible(int[] arr, int n, int m,
                           int curr_min)
    {
        int studentsRequired = 1;
        int curr_sum = 0;

        // iterate over all books
        for (int i = 0; i < n; i++) {
            // check if current number of
            // pages are greater than curr_min
            // that means we will get the
            // result after mid no. of pages
            if (arr[i] > curr_min)
                return false;

            // count how many students
            // are required to distribute
            // curr_min pages
            if (curr_sum + arr[i] > curr_min) {
                // increment student count
                studentsRequired++;

                // update curr_sum
                curr_sum = arr[i];

                // if students required becomes
                // greater than given no. of
                // students, return false
                if (studentsRequired > m)
                    return false;
            }

            // else update curr_sum
            else
                curr_sum += arr[i];
        }
        return true;
    }

    // function to find minimum pages
    static int findPages(int[] arr, int n, int m)
    {
        long sum = 0;

        // return -1 if no. of books
        // is less than no. of students
        if (n < m)
            return -1;
        int mx = arr[0];
        // Count total number of pages
        for (int i = 0; i < n; i++) {
            sum += arr[i];

            mx = (arr[i] > mx ? arr[i] : mx);
        }

        // initialize start as 0 pages
        // and end as total pages
        int start = 0, end = (int)sum;
        int result = int.MaxValue;

        // traverse until start <= end
        while (start <= end) {
            // check if it is possible to
            // distribute books by using
            // mid as current minimum
            int mid = (start + end) / 2;
            if (isPossible(arr, n, m, mid)) {
                // update result to current distribution
                // as it's the best we have found till now.
                result = mid;

                // as we are finding minimum and
                // books are sorted so reduce
                // end = mid -1 that means
                end = mid - 1;
            }

            else
                // if not possible means pages
                // should be increased so update
                // start = mid + 1
                start = mid + 1;
        }

        // at-last return
        // minimum no. of pages
        return result;
    }

    // Drivers code
    static public void Main()
    {

        // Number of pages in books
        int[] arr = { 12, 34, 67, 90 };
        int n = arr.Length;
        int m = 2; // No. of students

        Console.WriteLine("Minimum number of pages = "
                          + findPages(arr, n, m));
    }
}
JavaScript
// Utility method to check if current minimum value
// is feasible or not.
function isPossible(arr,n,m,curr_min)
{
    let studentsRequired = 1;
    let curr_sum = 0;
    
  
    // iterate over all books
    for (let i = 0; i < n; i++)
    {
        // check if current number of pages are greater
        // than curr_min that means we will get the result
        // after mid no. of pages
        if (arr[i] > curr_min)
            return false;
  
        // count how many students are required
        // to distribute curr_min pages
        if (curr_sum + arr[i] > curr_min)
        {
            // increment student count
            studentsRequired++;
  
            // update curr_sum
            curr_sum = arr[i];
  
            // if students required becomes greater
            // than given no. of students,return false
            if (studentsRequired > m)
                return false;
        }
  
        // else update curr_sum
        else
            curr_sum += arr[i];
    }
    return true;
}

// method to find minimum pages
function findPages(arr,n,m)
{
    let sum = 0;
    let mx = arr[0] ;
  
    // return -1 if no. of books is less than
    // no. of students
    if (n < m)
        return -1;
  
    // Count total number of pages
    for (let i = 0; i < n; i++){
     sum += arr[i];
     mx = (arr[i] > mx ? arr[i] : mx) ;
    }
       
  
    // initialize start as 0 pages and end as
    // total pages
    let start = 0, end = sum;
    let result = Number.MAX_VALUE;
  
    // traverse until start <= end
    while (start <= end)
    {
        // check if it is possible to distribute
        // books by using mid as current minimum
        let mid =Math.floor( (start + end) / 2);
        if (isPossible(arr, n, m, mid))
        {
            // if yes then find the minimum distribution
            result = Math.min(result, mid);
  
            // as we are finding minimum and books
            // are sorted so reduce end = mid -1
            // that means
            end = mid - 1;
        }
  
        else
            // if not possible means pages should be
            // increased so update start = mid + 1
            start = mid + 1;
    }
  
    // at-last return minimum no. of  pages
    return result;
}

// Driver Method
let arr=[12, 34, 67, 90];
let m = 2; //No. of students
console.log("Minimum number of pages = " +
                          findPages(arr, arr.length, m));
PHP
<?php

// Utility function to check if current
// minimum value is feasible or not.

function isPossible($arr, $n, $m, 
                    $curr_min)
{
    $studentsRequired = 1;
    $curr_sum = 0;

    // iterate over all books
    for ( $i = 0; $i < $n; $i++)
    {
        // check if current number of pages 
        // are greater than curr_min that
        // means we will get the result 
        // after mid no. of pages
        if ($arr[$i] > $curr_min)
            return false;

        // count how many students are
        // required to distribute
        // curr_min pages
        if ($curr_sum + $arr[$i] > $curr_min)
        {
            // increment student count
            $studentsRequired++;

            // update curr_sum
            $curr_sum = $arr[$i];

            // if students required becomes 
            // greater than given no. of 
            // students, return false
            if ($studentsRequired > $m)
                return false;
        }

        // else update curr_sum
        else
            $curr_sum += $arr[$i];
    }
    return true;
}

// function to find minimum pages
function findPages($arr, $n, $m)
{
    $sum = 0;

    // return -1 if no. of books is 
    // less than no. of students
    if ($n < $m)
        return -1;

    // Count total number of pages
    for ($i = 0; $i < $n; $i++)
        $sum += $arr[$i];

    // initialize start as 0 pages 
    // and end as total pages
    $start = 0;
    $end = $sum;
    $result = PHP_INT_MAX;

    // traverse until start <= end
    while ($start <= $end)
    {
        // check if it is possible to 
        // distribute books by using 
        // mid as current minimum
        $mid = (int)($start + $end) / 2;
        if (isPossible($arr, $n, $m, $mid))
        {
            // update result to current distribution
              // as it's the best we have found till now
            $result = $mid;

            // as we are finding minimum and 
            // books are sorted so reduce 
            // end = mid -1 that means
            $end = $mid - 1;
        }

        else
            // if not possible means pages 
            // should be increased so update 
            // start = mid + 1
            $start = $mid + 1;
    }

    // at-last return minimum
    // no. of pages
    return $result;
}

// Driver code

// Number of pages in books
$arr = array(12, 34, 67, 90);
$n = count($arr); 
$m = 2; // No. of students

echo "Minimum number of pages = ",
    findPages($arr, $n, $m), "\n";

?>

Output
Minimum number of pages = 113

Time Complexity: O(N*log(N)), Where N is the total number of pages in the book.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Allocate minimum number of pages (Non Consecutive)
Given the number of pages in N different books and M students. Every student is assigned to read some books that can be consecutive or non-consecutive. The task is to assign books so that the maximum number of pages assigned to a student is minimum. Examples: Input: pages = {8, 15, 10, 20, 8}, M = 2Output: 31Explanation: One optimal distribution is
7 min read
How to dynamically allocate a 3D array in C++
Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to
4 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
Minimum and maximum number of N chocolates after distribution among K students
Given N Chocolates and K students, the task is to find how to divide the chocolates such that the difference between the minimum and maximum chocolate received by all students is minimized. Print the value of minimum and maximum chocolate distribution.Examples: Input: N = 7, K = 3 Output: Min = 2, Max = 3 Distribution is 2 2 3 Input: N = 100, K = 1
3 min read
Find minimum cost to buy all books
Given an array of ratings for n books. Find the minimum cost to buy all books with below conditions : Cost of every book would be at-least 1 dollar.A book has higher cost than an adjacent (left or right) if rating is more than the adjacent. Examples : Input : Ratings[] = {1, 3, 4, 3, 7, 1} Output : 10 Exp :- 1 + 2 + 3 + 1 + 2 + 1 = 10 Input : ratin
6 min read
Maximum number of chocolates to be distributed equally among k students
Given n boxes containing some chocolates arranged in a row. There are k number of students. The problem is to distribute maximum number of chocolates equally among k students by selecting a consecutive sequence of boxes from the given lot. Consider the boxes are arranged in a row with numbers from 1 to n from left to right. We have to select a grou
9 min read
Number of ways to distribute N Paper Set among M students
Given N students and a total of M sets of question paper where M ? N. All the M sets are different and every sets is available in sufficient quantity. All the students are sitting in a single row. The task is to find the number of ways to distribute the question paper so that if any M consecutive students are selected then each student has a unique
4 min read
Maximum profit that can be obtained by buying at most K books
Given an integer K and an array arr[] consisting of N integers, where an array element arr[i] represents the price of the ith book. Profit of buying ith book represents max(0, -1 * arr[i]), the task is to find the maximum profit possible by buying at most K books. Examples: Input: arr[] = {-10, 20, -30, 50, -19}, K = 2Output: 49Explanation: Maximum
6 min read
7 Best Books for Competitive Programming
Do you have a dream to win a Gold Medal in the Olympics of Programming (ACM ICPC)? Do you want to ace your career with Google Kickstart or want to win a prize amount of $20,000 to become a world champion in Facebook Hackercup or Google Code jam? Then you have to be an out-of-the-box problem solver. These are some most famous global algorithmic prog
7 min read
Best Data Structures and Algorithms Books
Data Structures and Algorithms is one of the most important skills that every Computer Science student must have. There are a number of remarkable publications on DSA in the market, with different difficulty levels, learning approaches and programming languages. In this article we're going to discuss a summary of top 10 Best Data Structures and Alg
9 min read
CSES Solutions - Reading Books
There are N books, and Kotivalo and Justiina are going to read them all. For each book, you know the time it takes to read it, given as arr[] such that arr[i] is the time it takes to read ith book. They both read each book from beginning to end, and they cannot read a book at the same time. What is the minimum total time required? Examples: Input:
7 min read
Why is programming important for first year or school students?
Although computer programming was once seen as a skill reserved for geeks and computer nerds, it’s now regarded as an essential ability for 21st century learners and is becoming a key component of many curriculums, even in primary schools. And as it is becoming essential to learning programming basics in school itself, you need to be ahead of those
6 min read
Maximum students to pass after giving bonus to everybody and not exceeding 100 marks
Given an array [Tex]arr [/Tex]which represents the marks of [Tex]n [/Tex]students. The passing grade is [Tex]50 [/Tex]and maximum marks that a student can score is [Tex]100 [/Tex], the task is to maximize the student that are passing the exam by giving bonus marks to the students. Note that if a student is given bonus marks then all other students
6 min read
Distribution of candies according to ages of students
Given two integer arrays ages and packs where ages store the ages of different students and an element of pack stores the number of candies that packet has (complete array represent the number of packets). The candies can be distributed among students such that: Every student must get only one pack of candies.All students of the same age must get e
11 min read
Program to calculate Percentile of Students
Given an array containing marks of students, the task is to calculate the percentile of the students. The percentile is calculated according to the following rule: The percentile of a student is the % of the number of students having marks less than him/her. Examples: Input: arr[] = { 12, 60, 80, 71, 30 }Output: { 0, 50, 100, 75, 25 }Explanation: P
5 min read
Check wifi is available to all students or not
Given a binary string S of length N, where S[i] = '1' represents the presence of a wifi in the ith room and S[i] = '0' represents no wifi. Each wifi has range X i.e. if there is a wifi in the ith room then its range will go up to X more rooms on its left as well as right. Find whether students in all rooms can use wifi or not. Examples: Input: N =
7 min read
Queries to count groups of N students possible having sum of ratings within given range
Given integers N and K representing the number of batches and number of students in each batch respectively, and a 2D array ratings[][] of size N * K where each row has ratings for every K students and Q queries of type {a, b}. The task for each query is to count the number of groups of N students possible by selecting a student from each batch, su
15+ min read
Distributing Blueberry Cheese Cake among Students
There is a school in a village. It has N classes. One fine day, someone donated B blueberry cheesecakes to schools. Now you need to divide these cakes such that: Each class gets at least 1 cake.Each class will share the cake(s) among students.Your aim is to minimize the maximum number of students per cake in any class.Examples: Input: N = 1, B = 2,
15 min read
Merge details of students (Merging Details)
Bob, a teacher of St. Joseph School given a task by his principal to merge the details of the students where each element details[i] is a list of strings, where the first element details[i][0] is a name of the student, and the rest of the elements are emails representing emails of the student. Two details belong to the same student if there is some
9 min read
Find the Maximum Score Achieved by at Least K Students
Given an array of integers scores[], where scores[i] represents the score of the i-th student in a class, return the maximum value of k such that: At least k students achieved a score of k or more.Each of those k students scored at least k marks.Examples: Input: scores = [3, 5, 2, 6, 4, 5]Output: 4Explanation: The maximum value of k is 4 because th
3 min read
Minimize Maximum Waiting Time for Students and Buses
Given N number of students and M number of buses with each of them having a capacity of C. The time of arrival of N students is given by an array arr[] where i'th index (1 ≤ i ≤ N) denotes the time of arrival of the ith student, the task is to find the smallest value of the maximum waiting time any student has to wait. Note: Waiting time is the dif
8 min read
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number
Given two numbers N and M, the task is to find the minimum number of moves to change N to M or -1 if it's impossible. In one move, add to the current number any of its divisors not equal to 1 and the number itself. Examples: Input: N = 4, M = 24Output: 5Explanation: the number 24 can be reached starting from 4 using 5 operations: 4-&gt;6-&gt;8-&gt;
15+ min read
Split array into minimum number of subsets with every element of a subset divisible by its minimum
Given an array arr[] of size N, the task is to split the array into the minimum number of subsets such that every element belongs to exactly one subset and is divisible by the minimum element present in each subset. Examples: Input: arr[] = {10, 2, 3, 5, 4, 2}Output: 3Explanation:The three possible groups are: {5, 10}, where all the element is divi
7 min read
Split array into minimum number of subsets having difference between maximum and minimum element at most K
Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum number of sets, the array elements can be divided into such that the difference between the maximum and minimum element of each set is at most K. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 2Explanation:The given array can be divided into two
6 min read
Maximum and minimum of an array using minimum number of comparisons
Given an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons. Examples: Input: arr[] = {3, 5, 4, 1, 9}Output: Minimum element is: 1 Maximum element is: 9 Input: arr[] = {22, 14, 8, 17, 35, 3}Output: Minimum element is: 3 Maximum element is: 35 Maximum and minimum of an array
15+ min read
Minimum number using set bits of a given number
Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number. Examples : Input : 6 Output : 3 Binary representation of 6 is 0000....0110. Smallest number with same number of set bits 0000....0011. Input : 11 Output : 7 Simple Approach: 1. Find binary representation of the number using simple
4 min read
Minimum number of cubes whose sum equals to given number N
Given an integer n, the task is to find the minimum number of cubes whose sum equals N.Examples: Input: N = 496 Output: 3 43 + 63 + 63 = 496 Note that 13 + 33 + 53 + 73 = 496 but it requires 4 cubes.Input: N = 15 Output: 8 Naive approach: Write a recursive method that will take every perfect cube less than N say X as part of the summation and then
10 min read
Find a number which give minimum sum when XOR with every number of array of integers
Given an array arr[] of non-negative integers, the task is to find an integer X such that (arr[0] XOR X) + (arr[1] XOR X) + ... + arr[n - 1] XOR X is minimum possible.Examples: Input: arr[] = {3, 9, 6, 2, 4} Output: X = 2, Sum = 22Input: arr[] = {6, 56, 78, 34} Output: X = 2, Sum = 170 Approach: We will check 'i'th bit of every number of the array
8 min read
Minimum number of Binary strings to represent a Number
Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples: Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 111 111 111 110 10 Approach: Store all digits of the
7 min read
Smallest number dividing minimum number of elements in the array | Set 2
Given an array arr[] of N integers, the task is to find the smallest number that divides the minimum number of elements from the array. Examples: Input: arr[] = {2, 12, 6} Output: 5 Here, 1 divides 3 elements 2 divides 3 elements 3 divides 2 elements 4 divides 1 element 5 divides no element 6 divides 2 elements 7 divides no element 8 divides no ele
6 min read