Problem Description
Given an array of positive integers and a sequence of removal queries, each query removes an element from the array. The removal can split the array into several contiguous segments of remaining positive integers. After each removal query, the task is to determine the maximum segment sum (i.e., the sum of a contiguous block) among all segments. The twist is that the queries are applied one-by-one, and we need to output the maximum segment sum after each removal.
Key Insights
- Instead of processing removals in the given order, we can reverse the process by instead "adding" elements back.
- In the reverse process, initially treat the array as completely removed (all zeros) and add back elements in the reverse order of removal.
- When adding an element, check its immediate neighbors. If any neighbor has already been added (i.e. belongs to a segment), merge these segments.
- Use a Union Find (Disjoint Set Union) data structure to efficiently merge segments and maintain the total sum for each segment.
- Keep a global variable to track the maximum segment sum seen so far.
- Finally, the results obtained during the reverse simulation should be reversed to match the original order of removals.
Space and Time Complexity
Time Complexity: O(n · α(n)) ≈ O(n) per query, where n is the length of the array and α(n) is the inverse Ackermann function (almost constant). Space Complexity: O(n) for the Union Find data structure and auxiliary arrays.
Solution
We use a reverse process: start from an empty array and add elements in reverse order of removals. When an element is added, it starts as its own segment. Then check and merge with left and right neighbors (if they are already added) using the Union Find structure. The DSU keeps track of the parent, the size of the segment, and importantly the segment sum. After each addition, update the maximum sum. Finally, reverse the series of maximum sums we collected during the reverse simulation to return the answer in the order of removals.