#K60462. Maximum Nested Depth of Parentheses
Maximum Nested Depth of Parentheses
Maximum Nested Depth of Parentheses
Given a string s
which consists only of characters '(' and ')', determine the maximum depth of nested parentheses. The depth is defined as the maximum number of open parentheses that have not yet been closed. The function should return -1 if the string is not a valid parentheses sequence (i.e. there is any unmatched parenthesis).
For a valid string:
- The empty string has a depth of 0.
- A single pair "()" has a depth of 1.
- Nested pairs like "(())" have a depth of 2, and so on.
If the sequence is not properly nested, return -1
.
Mathematically, if we denote by \( d(i) \) the nesting depth at position \( i \), then we have:
\[ d(i) = \begin{cases} d(i-1)+1 & \text{if } s[i] = '(' \\ d(i-1)-1 & \text{if } s[i] = ')' \end{cases} \]and the answer is \( \max_i d(i) \) if the sequence is valid (i.e. \( d(n) = 0 \) and \( d(i) \ge 0 \) for all \( i \)).
inputFormat
The input is provided via standard input (stdin) as a single line containing a string s
consisting only of the characters '(' and ')'.
outputFormat
Output the maximum nested depth of the parentheses if the input string is properly nested. If the sequence is invalid (i.e., it contains unmatched parentheses), output -1
.
(())
2