Problem
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index
removeQueries[i] is removed, splitting nums into different segments.
A segment is a contiguous sequence of positive integers in nums. A
segment sum is the sum of every element in a segment.
Return an integer arrayanswer , of lengthn , whereanswer[i]_is themaximum segment sum after applying the _ith removal.
Note: The same index will not be removed more than once.
Examples
Example 1
| |
Example 2
| |
Constraints
n == nums.length == removeQueries.length1 <= n <= 10^51 <= nums[i] <= 10^90 <= removeQueries[i] < n- All the values of
removeQueriesare unique.
Solution
Method 1 – Union-Find with Segment Tracking
Intuition
We process removals in reverse (i.e., we “add back” elements), using union-find to dynamically merge segments and track their sums. This allows us to efficiently maintain the maximum segment sum after each removal.
Approach
- Initialize all elements as removed (inactive).
- Process removeQueries in reverse, each time activating the removed index.
- Use union-find to merge adjacent active segments and maintain their sums.
- After each addition, update the current maximum segment sum.
- Store the result for each step, then reverse the answer at the end.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n α(n)), whereα(n)is the inverse Ackermann function for union-find. Each union/find operation is nearly constant time, and we do O(n) operations. - 🧺 Space complexity:
O(n), for the parent, segment sum, and active arrays.