#K10186. Stack Operations with Maximum Retrieval
Stack Operations with Maximum Retrieval
Stack Operations with Maximum Retrieval
You are given one or more datasets containing a sequence of operations on a stack. Each dataset begins with an integer that indicates the number of operations in the dataset, followed by that many lines of operations. The operations come in three types:
- Push X – Push the integer X onto the stack.
- Pop – Remove the top element from the stack. If the stack is empty, do nothing.
- Max – Print the maximum element in the stack. If the stack is empty, do nothing.
For every Max
operation, you must print the current maximum element in the stack on a new line, processing the operations sequentially as they appear in the input across all datasets.
Note: A line containing a single '-' indicates the end of the input.
The task requires careful maintenance of the stack and an auxiliary structure that efficiently tracks the maximum element.
inputFormat
The input is read from stdin and consists of multiple datasets. Each dataset starts with a line containing an integer N, which represents the number of operations. Then follow N lines, each containing one of the three operations: "Push X", "Pop", or "Max". The input terminates with a line containing a single '-' character.
outputFormat
For every "Max" operation encountered in the processing of all datasets, print the maximum element in the stack on its own line. If the stack is empty when a "Max" operation is encountered, no output should be produced for that operation.## sample
5
Push 1
Push 2
Max
Pop
Max
4
Push 10
Max
Push 5
Max
-
2
1
10
10
</p>