Problem Description
Given an integer array nums, you are allowed to perform at most one operation: choose any integer x (ensuring that after removing all occurrences of x the array is non‐empty) and remove every occurrence of x from nums. After at most one such removal, return the maximum subarray sum of the resulting array. (A subarray is a contiguous subsequence of the array.)
Key Insights
- Without any removal, the maximum subarray sum can be computed by using Kadane’s algorithm.
- Removing a value x from the array “breaks” the array into several segments – the remaining array is the concatenation of the subarrays that exist between occurrences of x.
- For a candidate x, the maximum subarray sum in the resulting array is the result of “merging” these segments optimally.
- A segment tree (or any range query data structure) can be pre-built over the original nums array to answer maximum subarray sum queries over arbitrary intervals. Each candidate’s remaining segments (which are disjoint intervals) can be quickly queried and then merged (via a standard combine operation) to obtain the “global” maximum subarray sum for that candidate.
- Finally, the answer is the maximum over (i) the baseline (no removal) and (ii) the value obtained after performing the removal for each candidate x (provided after removal the array isn’t empty).
Space and Time Complexity
Time Complexity: O(n log n)
- Building a segment tree takes O(n).
- For each candidate we perform queries over a few intervals (the total number of queries is proportional to n over all candidates) and each query takes O(log n). Space Complexity: O(n)
- For the segment tree and additional dictionaries used for mapping candidates to their positions.
Solution
We solve the problem in two phases.
- Compute the baseline maximum subarray sum on the original array using Kadane’s algorithm.
- Preprocess the array into a segment tree. A tree node stores four values: total sum, maximum prefix sum, maximum suffix sum, and maximum subarray sum. For every distinct candidate x (that appears in nums and does not remove the entire array), obtain the list of indices where x occurs. Removing x splits the array into intervals: • From index 0 to pos[0]-1, • Between two successive occurrences, • From pos[last]+1 to the end. Use the segment tree to query each of these intervals and then “merge” the results sequentially – this mimics concatenating the segments.
- The answer is the maximum value found among the baseline and each removal candidate option.
The trick is that merging the segments is done with the standard segment tree “combine” function and using the pre-built tree means that each range query is efficient rather than scanning each interval.