Skip to content

1614. Maximum Nesting Depth of the Parentheses πŸ‘ΒΆ

  • Time: O(n)O(n)
  • Space: O(1)O(1)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int maxDepth(string s) {
    int ans = 0;
    int opened = 0;

    for (const char c : s)
      if (c == '(')
        ans = max(ans, ++opened);
      else if (c == ')')
        --opened;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int maxDepth(String s) {
    int ans = 0;
    int opened = 0;

    for (final char c : s.toCharArray())
      if (c == '(')
        ans = Math.max(ans, ++opened);
      else if (c == ')')
        --opened;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maxDepth(self, s: str) -> int:
    ans = 0
    opened = 0

    for c in s:
      if c == '(':
        opened += 1
        ans = max(ans, opened)
      elif c == ')':
        opened -= 1

    return ans
Buy Me A Coffee
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! πŸ˜„