Commented solution for beginners
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        stack<int> stk;     // Create a stack to keep track of indices\n        stk.push(-1);       // Initialize the stack with -1 as a base index\n        int ans = 0;        // Initialize the answer variable to store the maximum length\n\n        for(int i = 0; i < s.size(); i++) {\n            if(s[i] == \'(\')\n                stk.push(i);  // Push the index of an opening parenthesis onto the stack\n            else {\n                if(stk.size() == 1)\n                    stk.top() = i;  // If stack contains only the base index, update it to the current index\n                else {\n                    stk.pop();       // Pop the top index from the stack\n                    ans = max(ans, i - stk.top());  // Calculate the current valid length and update the answer\n                }\n            }\n        }\n        return ans;   // Return the maximum valid length\n    }\n};\n\n```
['C++']