A - 連続勝利の記録 / Record of Consecutive Wins 解説 by admin
Claude 4.6 Opus (Thinking)Overview
This is a problem of finding the longest consecutive sequence of W characters in a string. It is a classic problem of finding the “longest run (run-length)”.
Analysis
Essence of the Problem
We need to find the maximum number of times W appears consecutively without interruption in string S.
For example, if S = "WWLWWWLW", the consecutive W segments are as follows:
- WW at the beginning → length 2
- WWW in the middle → length 3
- W at the end → length 1
Therefore, the answer is 3.
Comparison with a Naive Approach
Using a double loop to check “the length of consecutive Ws starting from each position” would take \(O(N^2)\), which could result in TLE (Time Limit Exceeded) given the constraint that \(N\) can be up to \(10^6\).
However, we can find the answer by scanning the string just once. The method is: increment a counter when W appears, and reset the counter when L appears. This takes only \(O(N)\).
Algorithm
- Initialize variables
count(current length of consecutiveWs) andmax_count(maximum value so far) to \(0\). - Scan through string
Sone character at a time from the beginning:- If the character is
W, incrementcountby \(1\) and updatemax_count. - If the character is
L, resetcountto \(0\).
- If the character is
- Output
max_countat the end.
Step-by-step Example (S = "WWLWWWLW")
| Position | Character | count |
max_count |
|---|---|---|---|
| 0 | W | 1 | 1 |
| 1 | W | 2 | 2 |
| 2 | L | 0 | 2 |
| 3 | W | 1 | 2 |
| 4 | W | 2 | 2 |
| 5 | W | 3 | 3 |
| 6 | L | 0 | 3 |
| 7 | W | 1 | 3 |
The final answer is max_count = 3.
Complexity
- Time Complexity: \(O(N)\) — only a single scan through the string
- Space Complexity: \(O(N)\) — \(O(N)\) for storing string \(S\), and \(O(1)\) for all other variables
Implementation Notes
The update of
max_countshould be done at the momentWis found (immediately after incrementingcount). An alternative approach of updating collectively when encounteringLis possible, but it may miss an update when the string ends withW, so updating at theWtiming is safer.If there are no
Wcharacters at all,countis never incremented, somax_countremains at its initial value of \(0\) and is output as is. This is consistent with the problem’s specification.Source Code
N = int(input())
S = input()
max_count = 0
count = 0
for c in S:
if c == 'W':
count += 1
if count > max_count:
max_count = count
else:
count = 0
print(max_count)
This editorial was generated by claude4.6opus-thinking.