Editorial
Call an interval a minimal MEX interval if no smaller nonempty subinterval of has the same MEX. Every interval of length is minimal.
All are nonnegative. If an endpoint can be removed without changing the MEX, removing it does not increase the cost sum. Repeating this operation produces a minimal MEX interval with the same MEX and a score no smaller than the original score. Therefore, only minimal MEX intervals can be optimal.
For a minimal interval of length at least , we have .
First suppose . Removing the right endpoint must change the MEX, so
For a fixed right endpoint , there is a unique largest satisfying this condition. Let be the last occurrence of up to position . Then
All required values must exist, and the previous occurrence of must be before so that removing position changes the MEX.
The case is symmetric. Let be the first occurrence of at or after . Then the candidate endpoint is
and the next occurrence of must be after .
The first case contributes at most one candidate for each , and the second case contributes at most one candidate for each . Together with all singleton intervals, there are only candidates.
During a left-to-right scan, maintain the last occurrence of every value in a segment tree. We need the minimum over a value prefix and the smallest value whose stored position is less than a given ; the latter is the interval MEX. A symmetric right-to-left scan maintains next occurrences. All minimal intervals are found in time.
For every candidate , compute
where is the prefix sum of .
Sort queries by their right endpoint. Sort candidates by and add every candidate with not exceeding the current query endpoint. A segment tree indexed by stores the maximum weight added at each start position. The answer to query is the maximum over start positions . Every added candidate already satisfies , so this is exactly the set of candidates contained in the query interval.
The total time complexity is and the memory complexity is .