Wednesday, February 24, 2021

Published February 24, 2021 by Anonymous with 0 comment

Minimum number of chairs required to ensure that every worker is seated at any instant

Minimum number of chairs required to ensure that every worker is seated at any instant

Given a string S representing the record of workers entering and leaving the rest area, where E represents entering and L represents leaving the rest area. For each worker, one chair is required. The task is to find the minimum number of chairs required so that there is no shortage of chairs at any given time.

Examples:

Input: S = “EELEE”
Output: 3
Explanation:
Step 1: One person enters. Therefore, 1 chair is required for now.
Step 2: Another person enters. Therefore, the number of chairs are required to be increased to 2.
Step 3: One person leaves. Therefore, no need to increase the number of chairs.
Step 4: Another person enters. Still, no need to increase the number of chairs.
Step 4: Another person enters. Theefore, number of chairs are needed to be increased to 3.
Therefore, minimum 3 chairs are required such that there is never a shortage of chairs.

Input: S = “EL”
Output: 1

Approach: Follow the steps below to solve the problem:


  • Initialize a variable, say count.
  • Iterate over the characters of the string using a variable, say i.
  • If the ith character is ‘E’, then increase the count by 1, as more number of chairs are required.
  • If the ith character is ‘L’, then decrease the count by 1 as one of the chair is emptied.
  • Print the maximum value of count obtained at any step.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

  

int findMinimumChairs(string s)

{

    

    

    int count = 0;

  

    

    int i = 0;

  

    

    

    int mini = INT_MIN;

  

    

    while (i < s.length()) {

  

        

        if (s[i] == 'E')

  

            

            count++;

  

        

        else

            count--;

  

        

        

        mini = max(count, mini);

  

        i++;

    }

  

    

    return mini;

}

  

int main()

{

    

  

    

    string s = "EELEE";

  

    

    

    cout << findMinimumChairs(s);

}

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment