A - 連続勝利の記録 / Record of Consecutive Wins 解説 by admin
GPT 5.4 HighOverview
By scanning the string \(S\) from left to right, counting how many consecutive Ws there are, and keeping track of the maximum value, we can find the answer.
In other words, this is simply a problem of maintaining the “current winning streak” and the “maximum winning streak so far.”
Analysis
What we want in this problem is the length of the longest consecutive run of Ws in the string \(S\).
For example, if
- \(S =\)
WWLWWWLW
then the consecutive runs of W are:
WW→ length \(2\)WWW→ length \(3\)W→ length \(1\)
so the answer is \(3\).
Key Observation
When scanning the string from left to right:
- If the character is
W, increment the current consecutive count by \(1\) - If the character is
L, the streak is broken, so reset it to \(0\)
This way, we can determine the “length of the current consecutive W run” at each point.
By continuously taking the maximum of this value, we obtain the answer.
Naive Approach
One could also consider checking “how far W continues” starting from each position.
However, with this approach, in the worst case we would need to look far ahead from each position, resulting in a time complexity of \(O(N^2)\).
Since the constraint is \(N \le 10^6\), \(O(N^2)\) is too slow.
How to Solve It
We just need a single pass through the string. By maintaining only the “current consecutive count” and the “maximum value,” we can find the answer by examining each character exactly once.
Algorithm
Prepare the following two variables:
cur: the number of consecutiveWs currently in a rowans: the maximum consecutive count seen so far
Scan the string \(S\) from left to right:
- When the character is
W: Setcur += 1, then updateans = max(ans, cur) - When the character is
L: The streak is broken, so setcur = 0
Finally, output ans.
Example
\(S =\) WLWWWWLLW
Processing each character in order:
W→cur = 1,ans = 1L→cur = 0W→cur = 1,ans = 1W→cur = 2,ans = 2W→cur = 3,ans = 3W→cur = 4,ans = 4L→cur = 0L→cur = 0W→cur = 1,ans = 4
Therefore, the answer is \(4\).
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\)
Implementation Notes
When encountering
L, always reset the current consecutive countcurto \(0\).Even when there are no
Ws at all, initializingansto \(0\) will correctly produce the right output.Since \(N\) can be large, this method of scanning the entire string exactly once is well-suited for the problem.
Source Code
import sys
def main():
input = sys.stdin.readline
N = int(input())
S = input().strip()
ans = 0
cur = 0
for ch in S:
if ch == 'W':
cur += 1
if cur > ans:
ans = cur
else:
cur = 0
print(ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.4-high.