Python Saved Program: ferrous-home

facebook share

Here's the online compiler accompanied with IDE at your service. This is a saved code by one of our users. Try it out or save your own from the IDE page and don't forget to leave a feedback. You can find that at the bottom of the page.


def maxDepth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in xrange(n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        elif S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
Execute

Output

Press the execute button or CTRL + enter to run code.

Inputs