LeetCode Entry

1614. Maximum Nesting Depth of the Parentheses

04.04.2024 easy 2024 kotlin rust

Max nested parenthesis

1614. Maximum Nesting Depth of the Parentheses easy blog post substack youtube 2024-04-04_09-03.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/560

Problem TLDR

Max nested parenthesis #easy

Intuition

No special intuition, just increase or decrease a counter.

Approach

  • There is a maxOf in Kotlin, but solution is not pure functional. It can be with fold.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


  fun maxDepth(s: String): Int {
    var curr = 0
    return s.maxOf {
      if (it == '(') curr++
      if (it == ')') curr--
      curr
    }
  }


  pub fn max_depth(s: String) -> i32 {
    let (mut curr, mut max) = (0, 0);
    for b in s.bytes() {
      if b == b'(' { curr += 1 }
      if b == b')' { curr -= 1 }
      max = max.max(curr)
    }
    max
  }