公式

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

  1. Initialize variables count (current length of consecutive Ws) and max_count (maximum value so far) to \(0\).
  2. Scan through string S one character at a time from the beginning:
    • If the character is W, increment count by \(1\) and update max_count.
    • If the character is L, reset count to \(0\).
  3. Output max_count at 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_count should be done at the moment W is found (immediately after incrementing count). An alternative approach of updating collectively when encountering L is possible, but it may miss an update when the string ends with W, so updating at the W timing is safer.

  • If there are no W characters at all, count is never incremented, so max_count remains 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.