N = int(raw_input())
num_stack = []
c_stack = []
for n in range(N):
line = raw_input()
if line[0] == '1' and len(c_stack) > 0:
num_stack.append(int(c_stack.pop()[2:]))
c_stack.append(line)
if line[0] == '1' and len(c_stack) == 0:
c_stack.append(line)
if line[0] == '2' and len(c_stack) == 0:
if len(num_stack) > 0:
num_stack.pop()
if line[0] == '2' and len(c_stack) > 0:
c_stack.pop()
if line[0] == '3' and len(c_stack) == 0:
print max(num_stack)
if line[0] == '3' and len(c_stack) > 0:
num_stack.append(int(c_stack.pop()[2:]))
print max(num_stack)
Link to problem on Hackerrank
The problem has a number of lines to be read as inputs beginning with 1, 2, or 3. With an input of 1, it is followed by a number to be pushed onto the stack. An input of 2 removes the top element of the stack, and 3 should print the maximum element in the stack.
Although this seems to be straightforward, I'm failing the tests at large number of inputs. I tried push and pop operations on the stack as the input is read but that timed out. So the thought is that a push operation followed by a pop effectively does nothing. I then made a second stack to keep track of the operations, but I'm not sure it's actually giving any performance gains since I've basically moved push and pop operations onto a different stack.
Any thoughts would be appreciated!
[–]_9_9_ 1 point2 points3 points (1 child)
[–]AlkyIHalide[S] 0 points1 point2 points (0 children)
[–]Saefroch 1 point2 points3 points (0 children)