B - 果樹園の収穫区間 / Harvest Interval in the Orchard 解説 by admin
GPT 5.2 HighOverview
This problem asks you to find the length of the longest contiguous subarray where every tree’s sweetness falls within \([L, R]\).
Analysis
To satisfy the condition “all \(T_i\) in the interval satisfy \(L \le T_i \le R\)”, even a single out-of-range value makes the entire interval invalid.
In other words, we can rephrase the problem as:
- Find the maximum length of a consecutive run of elements satisfying \(L \le T_i \le R\).
If we naively try all intervals \([l,r]\), there are \(O(N^2)\) of them, and including the cost of checking each interval makes it even heavier. Since \(N \le 2 \times 10^5\), an \(O(N^2)\) approach will certainly not be fast enough (TLE).
Instead, we can efficiently find the maximum length by scanning from left to right once, keeping track of “how far the current consecutive valid run extends.”
Example: For \(T = [3, 5, 2, 4, 6]\), \(L=3\), \(R=5\)
Whether each element satisfies the condition: [○, ○, ×, ○, ×], so the longest consecutive run of ○ has length 2 (the first 3, 5).
Algorithm
- Let variable
curbe “the current consecutive length satisfying the condition,” andbestbe “its maximum value.” - Scan the array from left to right.
- If \(L \le x \le R\), then
cur += 1(the consecutive run extends) - Otherwise,
cur = 0(the consecutive run is broken, so reset)
- If \(L \le x \le R\), then
- At each step, update
best = max(best, cur). - The final
bestis the answer (if no interval satisfies the condition, it naturally remains 0).
This method simply counts the length of each consecutive block of elements satisfying the condition and takes the maximum.
Complexity
- Time complexity: \(O(N)\) (a single scan)
- Space complexity: \(O(1)\) (only a constant number of variables besides the input array)
Implementation Notes
The range check can be written concisely as
L <= x <= R(Python’s comparison chaining).When an out-of-range value is encountered, “no interval containing that position is valid,” so the consecutive length
curmust be reset to 0.Since the input can be large, reading it all at once with
sys.stdin.buffer.read()is faster and safer.Source Code
import sys
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
if not data:
return
N, L, R = data[0], data[1], data[2]
T = data[3:3+N]
best = 0
cur = 0
for x in T:
if L <= x <= R:
cur += 1
if cur > best:
best = cur
else:
cur = 0
print(best)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: