LeetCode Problem - Link


Problem

You are given a string s. Simulate events at each second i:

  • If s[i] == 'E', a person enters the waiting room and takes one of the chairs in it.
  • If s[i] == 'L', a person leaves the waiting room, freeing up a chair.

Return the minimum number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially empty.

 

Example 1:

Input: s = "EEEEEEE"

Output: 7

Explanation:

After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.



Sequential Approach

Before you solve this problem, know that the explanation is super misleading and very confusing. It's badly phrased and explained. Basically, what they are trying to ask is - what are the highest number of chairs required in the room at a point in time? You basically need to maintain a counter of max number of chairs required. I solved it this way


/**
 * @param {string} s
 * @return {number}
 */
var minimumChairs = function (s) {
    var entries = 0;
    var exits = 0
    var max = 0;
    
    for (let i = 0; i < s.length; i++) {
        if (s[i] == "E") {
            entries += 1
        } else {
            exits += 1
        }


        var current_max = entries - exits;
        if (current_max > max) {
            max = current_max
        }
    }


    return max
};