Official

B - 最大危険度区間 / Maximum Danger Interval Editorial by admin

GPT 5.2 High

Overview

By replacing whether each point is a “caution point” or not with \(+1/-1\), what we want to find becomes the “maximum subarray sum,” which can be solved in \(O(N)\) using Kadane’s algorithm.

Analysis

The danger level of an interval is defined as \(A - B\), where: - \(A\): the number of caution points - \(B\): the number of non-caution points

We transform each point \(i\) into the following value:

  • If \(L \le T_i \le R\) (caution point), then \(X_i = +1\)
  • Otherwise, \(X_i = -1\)

Then, the danger level of an interval \([l,r]\) equals [ (A-B)=\sum_{i=l}^{r} X_i ] In other words, the problem reduces to:

Find the maximum sum of a contiguous subarray of the array \(X\).

Why a naive approach doesn’t work

There are \(O(N^2)\) possible intervals. Even using prefix sums, computing the danger level for each interval takes \(O(N^2)\) overall, which is too slow for \(N \le 2\times 10^5\).

How to solve it

The maximum contiguous subarray sum can be computed in \(O(N)\) using the well-known Kadane’s algorithm, which maintains “the maximum sum ending at the current position.”

Example: \(X = [1, -1, 1, 1, -1]\) The maximum sum is \(2\), achieved by the interval \([3,4]\) (\(1+1\)), among others.

Algorithm

The idea behind Kadane’s algorithm:

  • \(cur\): the maximum danger level of an interval ending at the current position
  • \(best\): the maximum danger level seen so far

For each element \(x=X_i\), update as follows: [ cur = \max(x,\ cur+x) ]

This chooses whichever is better: - “Start a new interval (danger level \(x\)),” or - “Extend the previous good interval (danger level \(cur+x\)).”

Simultaneously, update the answer with: [ best = \max(best,\ cur) ]

In this problem, there is no need to actually store \(X_i\) in an array — it suffices to compute \(x=\pm 1\) while reading the input and update on the fly.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(1)\)

Implementation Notes

  • Even when all values are \(-1\), the interval length must be at least \(1\), so the answer can be negative. Therefore, initializing \(best\) to \(0\) would be incorrect. Instead, we initialize with the first element (in the code, we read \(T_1\) first and set \(cur=best=x\)).

  • Since the input is large, we use sys.stdin.buffer.read() for fast input reading.

    Source Code

import sys

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

    first_t = next(it)
    x = 1 if L <= first_t <= R else -1
    cur = best = x

    for _ in range(N - 1):
        t = next(it)
        x = 1 if L <= t <= R else -1
        cur = max(x, cur + x)
        best = max(best, cur)

    print(best)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.