查找进入或离开房间的最小和最大不同人员
给定一个二进制字符串people,其中'1'和'0'分别代表进入和离开房间的人。任务是找到进入或离开建筑物的最小和最大不同人员。
例子:
Input: “000”
Output: Minimum Persons: 3
Maximum Persons: 3
Explanation: 3 distinct persons left the building.
Input: “111”
Output: Minimum Persons: 3
Maximum Persons: 3
Explanation: 3 distinct persons entered the building.
Input: “110011”
Output: Minimum Persons: 2
Maximum Persons: 6
Explanation: 2 persons entered->those 2 persons left->same 2 persons entered
to account for minimum 2 persons.
All persons entered or left are distinct to account for maximum 6 persons.
Input: “10101”
Output: Minimum Persons: 1
Maximum Persons: 5
Explanation: 1 person entered- > he left -> again entered -> again left -> and again entered
to account for minimum 1 person.
All persons entered or left are distinct to account for maximum 5 persons.
方法:可以根据以下观察解决问题:
- Each person entering or leaving the room can be a unique person. This will give the maximum number of persons that can enter a room. This will be equal to the total number of times a leaving or entering operation is performed,
- Each time the same persons who are leaving the room are entering the room next time. So the maximum among the people leaving at a time or entering at a time is the minimum possible number of unique persons.
请按照下图进行更好的理解。
插图:
Consider persons = “10101”
For finding the maximum:
=> At first, first person (say P1) enters the room
=> Then, second person (say P2) exits the room
=> Then, third person (say P3) enters the room
=> Then, fourth person (say P4) exits the room
=> At last, fifth person (say P5) enters the room
Total 5 persons enter or leave the room at most.
For finding the minimum possible persons:
=> At first, first person (say P1) enters the room.
=> Then P1 exits the room.
=> Then P1 again enters the room.
=> Then again P1 exits the room.
=> At last P1 again enters the room.
So at least one person enters or leaves the room.
按照以下步骤实施上述观察:
- 开始遍历整个字符串people 。
- 如果people[i] = '1'然后递增输入并重新初始化退出到0 。
- 否则,如果people[i]='0'然后递增exited并重新初始化输入0 。
- 将{entered, exited}和N (字符串的大小)的最大值存储为对result的第一个和第二个值。
- 返回结果作为包含最小和最大不同人分别作为第一和第二值的最终对。
下面是上述方法的实现:
C++14
// C++ code to implement the approach
#include
using namespace std;
// Function to find the minimum and
// maximum number of possible persons
// entering or leaving the room
pair minDistPersons(string& persons)
{
int N = persons.length();
int entered = 0, exited = 0;
pair result = { 0, N };
for (int i = 0; i < N; i++) {
if (persons[i] == '1') {
entered++;
exited = 0;
}
else {
entered = 0;
exited++;
}
result.first
= max({ result.first, entered,
exited });
}
return result;
}
// Driver code
int main()
{
string persons = "10101";
// Function call
pair ans = minDistPersons(persons);
cout << "Minimum Persons: " << ans.first
<< "\n";
cout << "Maximum Persons: " << ans.second;
return 0;
}
Minimum Persons: 1
Maximum Persons: 5
时间复杂度: O(N)
辅助空间: O(1)