Sure, I should’ve explained my approach beforehand.
temp_stack - refers to the variable for storing the stack that contains the opening brackets.
MAX_DEPTH, MAX_DEPTH_START, MAX_LEN, and START_MAX are the variables in which I want to store the final values and print them.
Next, I’m iterating over every item on the list, given in the input.
Case 1: Stack is not empty
If the current element is 1, then I am adding it to the stack and incrementing the value of depth and max_len (temporary variables) by 1. I am also checking that if the current depth is greater than MAX_DEPTH, then I set the value of MAX_DEPTH as the current depth and the MAX_DEPTH_START (which stores the index of the first opening bracket where the maximum depth is reached).
If the current element is 2, then I decrease the value of the current depth by 1 but increase the value of max_len by 1 (as per the requirement of the question). Also, I am deleting the last element from the stack.
Case 2: The stack is empty
This means that we have successfully iterated over a “well-bracketed” sub-part. So, I checked whether the current max_len is greater than MAX_LEN or not. And change it accordingly. Then I reset the values of other temporary variables.
After iterating through all the elements I am just printing the values of
MAX_DEPTH, MAX_DEPTH_START, MAX_LEN, and START_MAX.
I also did a little change in the code and added
if MAX_LEN < max_len:
MAX_LEN = max_len
START_MAX = start_m
after iterating through all values. Now it’s failing only two tasks, out of 15.
Never thought that explaining my approach would result in me finding the mistake I made in the logic. Thanks, I figured it out!!