We want to calculate the longest valid parens. There are two cases, either the opening paren or the closing paren. With the opening paren, you can extend any possible len, otherwise, when you see a closing paren, you can calculate the longest valid paren ending at this location.

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack = [-1]
        max_len = 0
 
        for i, c in enumerate(s):
            if c == "(":
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    stack.append(i)
                else:
                    max_len = max(max_len, i - stack[-1])
        
        return max_len