I am attempting the matched brackets problem. I have written a Python program which seems to do the job but is very slow and thus exceeds the time limit. Please help me making this code more efficient. I have explained my code in the comments.
length = int(input()) inp = input().split(' ') inp = [ int(x) for x in inp ] position = 0 ##where our cursor is. highest_depth =0 buffer = 0 stretch = 0 ##max distance b/w two matched brackets. bar = 0 ## jst a buffer for calculating max distance between two brackets. stretch_pos = 0 for l in inp: position += 1 bar += 1 '''if the cursor is currently at open bracket(1) add 1 to buffer''' if l == 1: buffer += 1 else: '''if the cursor is at a closed bracket(2) we need to stop calculating higest depth and assign it to highest_depth only if the current value is smaller''' if highest_depth < buffer: highest_depth = buffer hpos = position -1 ##position of highest depth. buffer -= 1 '''if buffer is now 0 due to the above line it must mean that all the brackets opened have been closed.''' if buffer == 0: ''' bar which calculates the max distance between two matched brackets must be assigned now and reset to zero''' if bar > stretch: stretch = bar stretch_pos = position - stretch + 1 bar = 0 print(highest_depth , hpos,stretch, stretch_pos)