Skip to main content
5 of 6
edited title
Phrancis
  • 20.4k
  • 6
  • 68
  • 154

Push, Delete and Print stack elements

I've tried asking about the performance on the HackerRank discussion forum, it didn't work out.

The task is to write a program with three operations:

 1 x  Push the element x onto the stack.    
 2    Delete the element present at the top of the stack.   
 3    Print the maximum element in the stack.

The first input line is the number of lines in the program, all subsequent lines are one of the three instructions.

Sample Input:

 10
 1 97
 2
 1 20
 2
 1 26
 1 20
 2
 3
 1 91
 3

Sample Output:

 26
 91

My Solution:

data = []
for _ in range(int(input())):
    ins = input().split()
    if ins[0] == '1':
        data.append(int(ins[1]))
    elif ins[0] == '2':
        data.pop()
    else:
        print(max(data))

It gets slow on working with input size of 1000 elements or so, how could I speed this up?