B - 最大危険度区間 / Maximum Danger Interval Editorial by admin Editorial for printing
DeepSeek V3Overview
This problem requires determining whether each measurement point is a caution point, and then finding the maximum value of “number of caution points - number of non-caution points” among all contiguous subarrays.
Analysis
We transform each point as follows: - If it is a caution point (\(L \leq T_i \leq R\)), assign \(1\) - If it is a non-caution point, assign \(-1\)
Then, the problem reduces to “finding the maximum sum of a contiguous subarray in an array.” This is exactly the well-known “Maximum Subarray Sum” problem.
A naive approach (trying all contiguous subarrays) takes \(O(N^2)\) time, which is too slow given the constraint \(N \leq 2 \times 10^5\). Therefore, an efficient algorithm is needed.
Algorithm
This problem can be solved in \(O(N)\) using Kadane’s Algorithm. The steps are as follows:
- Transform each point to \(1\) if it is a caution point, or \(-1\) otherwise
- Apply Kadane’s Algorithm to the transformed array:
- Prepare a variable
current_sumto hold the current subarray sum and a variablemax_sumto hold the maximum subarray sum - Process the array from the beginning:
- Add the current element to
current_sum - If
current_sumis greater thanmax_sum, updatemax_sum - If
current_sumbecomes negative, reset it to 0 since it is better to start a new subarray from the next element
- Add the current element to
- Prepare a variable
Complexity
- Time complexity: \(O(N)\)
- \(O(N)\) for transforming the array
- \(O(N)\) for running Kadane’s Algorithm
- Space complexity: \(O(N)\)
- For storing the transformed array
Implementation Notes
Initial value settings: initialize
max_sumto a sufficiently small value (\(-10^{18}\)) andcurrent_sumto 0Works correctly even when all elements are negative (the maximum subarray sum will be the value of a single element)
It is clearer to first create a transformed array rather than processing the original array directly
Be mindful of the input value range (since \(N\) can be up to 200,000, an efficient algorithm is necessary)
Source Code
def main():
import sys
data = sys.stdin.read().split()
n = int(data[0])
L = int(data[1])
R = int(data[2])
T_list = list(map(int, data[3:3+n]))
arr = []
for t in T_list:
if L <= t <= R:
arr.append(1)
else:
arr.append(-1)
max_sum = -10**18
current_sum = 0
for num in arr:
current_sum += num
if current_sum > max_sum:
max_sum = current_sum
if current_sum < 0:
current_sum = 0
print(max_sum)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: