公式

A - 連続晴天の最長記録 / Longest Streak of Hot Days 解説 by admin

GPT 5.2 High

Overview

This is a problem where you check whether each day’s maximum temperature is \(K\) or above, and find the longest consecutive streak of “extremely hot days.”

Analysis

The “maximum length of a consecutive interval of extremely hot days” can be found simply by scanning the array from left to right while counting “how many consecutive extremely hot days we currently have.”

For example, if \(K=30\) and the temperatures are
\([29, 30, 31, 28, 30, 30]\): - Day 1 is not an extremely hot day, so the consecutive count is \(0\) - Days 2 and 3 are extremely hot days, so the consecutive count goes \(1 \rightarrow 2\) - Day 4 breaks the streak, so the consecutive count resets to \(0\) - Days 5 and 6 give \(1 \rightarrow 2\)

The maximum during this process is \(2\), so the answer is \(2\).

If you naively check “all intervals” to determine if they are consecutive, the number of intervals is \(O(N^2)\), which is far too slow for \(N \le 10^6\) (TLE).
Instead, we use a method that updates only the “current consecutive length” and “maximum value” in a single scan.

Algorithm

Prepare the following two variables:

  • cur: the length of the current consecutive streak of extremely hot days up to the position being examined
  • best: the maximum consecutive length encountered so far

Scan the array from left to right, and for each \(A_i\): - If \(A_i \ge K\), it is an extremely hot day, so set cur += 1 and update best = max(best, cur) - Otherwise, the streak is broken, so reset cur = 0

Finally, output best. If there were no extremely hot days at all, best remains \(0\), so \(0\) is output as-is.

Complexity

  • Time complexity: \(O(N)\) (just a single pass)
  • Space complexity: \(O(1)\) (no additional arrays, only variables)

Implementation Notes

  • Since \(N\) can be as large as \(10^6\), in Python it is safer to use sys.stdin.buffer.read().split() to read input quickly.

  • It is crucial to always reset cur to \(0\) when the streak is broken (forgetting this will lead to wrong answers).

    Source Code

import sys

def main():
    it = map(int, sys.stdin.buffer.read().split())
    N = next(it)
    K = next(it)

    best = 0
    cur = 0
    for _ in range(N):
        a = next(it)
        if a >= K:
            cur += 1
            if cur > best:
                best = cur
        else:
            cur = 0

    sys.stdout.write(str(best))

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

投稿日時:
最終更新: