Hackerrank problem ("Maximum Element")

N=int(input())
stack=[]
for i in range(N):
    a=list(map(int,input().split()))
    
    if a[0]==1:
        stack.append(a[1])
    elif a[0]==2:
        stack.pop()
    elif a[0]==3:
        print(max(stack))

Why is this code showing RunTime Error

Hackerrank does not tell you the type of error. It only shows AC or wrong.
Your code is not a runtime error, but a TLE. Finding max(stack) takes O(n) time, making your time complexity O(n^2). Your stack should be storing the prefix maximums, not the elements itself.

Correct Code
N=int(input())
stack=[]
stack.append(-1)
for i in range(N):
    a=list(map(int,input().split()))
    if a[0]==1:
        stack.append(max(stack[-1],a[1]))
    elif a[0]==2:
        stack.pop()
    elif a[0]==3:
        print(stack[-1])
2 Likes

From can i get the knowledge of time complexity and apply in the question as a beginner.

Try these questions.

1 Like

Also from where can I refer the theory for the above concepts.