B - 果樹園の収穫区間 / Harvest Interval in the Orchard 解説 by admin
Qwen3-Coder-480BOverview
Given a sequence of numbers, find the length of the longest contiguous subsequence where all values are at least \(L\) and at most \(R\).
Analysis
In this problem, we need to determine whether each interval \([l, r]\) satisfies the condition “all elements are at least \(L\) and at most \(R\).” A naive approach would be to exhaustively search all intervals using a double loop, but this results in \(O(N^2)\) time complexity, which cannot be processed within the time limit for the constraint \(N \leq 2 \times 10^5\) (TLE).
The key observation is that “intervals satisfying the condition must be contiguous.” In other words, by scanning from left to right while maintaining the length of the current contiguous valid interval, we can efficiently find the maximum length. Specifically, if the current element \(T_i\) is within the range, we increment the counter; if it is outside the range, we reset it.
For example, given the input:
N=6, L=3, R=5
T = [2, 3, 4, 5, 6, 4]
The intervals satisfying the condition are: - \([3, 4, 5]\) → length 3 (starting at position 1, ending at position 3) - \([4]\) → length 1 (starting at position 5)
Thus, the answer is 3.
Algorithm
- Use a variable
max_lento record the maximum length found so far. - Use a variable
current_lento record the length of the current contiguous valid interval. - Scan elements one by one from left to right, processing as follows:
- If \(L \leq T_i \leq R\), increment
current_lenby 1- Additionally, if
current_len > max_len, updatemax_len
- Additionally, if
- Otherwise, reset
current_lento 0
- If \(L \leq T_i \leq R\), increment
- Finally, output
max_len
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\) (excluding the input array)
Implementation Notes
sys.stdin.readis used for fast input reading.The condition check is a simple inequality \(L \leq T_i \leq R\).
If no valid interval exists,
max_lenremains at its initial value of 0, so no special handling is needed.Source Code
def main():
import sys
input = sys.stdin.read
data = input().split()
N = int(data[0])
L = int(data[1])
R = int(data[2])
T = list(map(int, data[3:]))
max_len = 0
current_len = 0
for i in range(N):
if L <= T[i] <= R:
current_len += 1
if current_len > max_len:
max_len = current_len
else:
current_len = 0
print(max_len)
if __name__ == "__main__":
main()
This editorial was generated by qwen3-coder-480b.
投稿日時:
最終更新: