A - 括弧の深さ / Depth of Parentheses Editorial by admin
Claude 4.5 OpusOverview
Given a correctly matched parenthesis sequence, the problem asks to find the maximum nesting depth of the parentheses.
Analysis
Key Insight
The depth of parentheses can be expressed as the number of ( characters that have appeared up to the current position minus the number of ) characters.
For example, looking at ((())) from left to right:
- ( → depth 1
- (( → depth 2
- ((( → depth 3 (this is the maximum)
- ((() → depth 2
- (()) → depth 1
- ()) → depth 0
In other words, the depth increases by 1 each time ( appears, and decreases by 1 each time ) appears.
Comparison with a Naive Approach
This problem can also be solved using a stack. The method involves pushing ( onto the stack and popping from the stack when ) appears. The maximum stack size becomes the answer.
However, in this problem, we don’t need to remember what was pushed onto the stack (since everything is (), so it’s sufficient to manage only the stack size with an integer variable. This reduces the space complexity from \(O(N)\) to \(O(1)\).
Algorithm
- Initialize variables
current_depth(current depth) andmax_depth(maximum depth) to \(0\) - Iterate through string \(S\) one character at a time from the beginning
- If
(: incrementcurrent_depthby \(1\) and updatemax_depth - If
): decrementcurrent_depthby \(1\)
- If
- The final
max_depthis the answer
Concrete Example
For input (()()):
| Position | Character | current_depth | max_depth |
|---|---|---|---|
| 0 | ( |
1 | 1 |
| 1 | ( |
2 | 2 |
| 2 | ) |
1 | 2 |
| 3 | ( |
2 | 2 |
| 4 | ) |
1 | 2 |
| 5 | ) |
0 | 2 |
The answer is \(2\).
Complexity
- Time complexity: \(O(|S|)\)
- Only a single scan through the string
- Space complexity: \(O(1)\)
- Only uses two variables, independent of input size
Implementation Notes
The update of
max_depthmust be done immediately after reading(. This is because the momentcurrent_depthincreases is when a new depth is reached.Since the parenthesis sequence is guaranteed to be correctly matched, there is no need to handle cases where
current_depthbecomes negative or doesn’t return to \(0\) at the end.Source Code
S = input()
max_depth = 0
current_depth = 0
for c in S:
if c == '(':
current_depth += 1
max_depth = max(max_depth, current_depth)
else: # c == ')'
current_depth -= 1
print(max_depth)
This editorial was generated by claude4.5opus.
posted:
last update: