↓Skip to main content
  1. LeetCode/

LeetCode 2382: Maximum Segment Sum After Removals

·2 mins· ·
LeetCode Hard Union-Find Prefix-Sum Ordered-Set Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-07-26

  • Submissions: Time Limit Exceeded ×2 → Accepted → Wrong Answer → Accepted

Approach
#

Removing elements one by one splits segments, but Union-Find can only merge. Work backward (Union-Find, work backward): start with everything removed and add elements back in reverse order, merging with existing neighbors on the left and right.

  • Each root stores its segment sum total[root].
  • In reverse, segments only grow and sums only increase (all numbers are positive), so a single variable holds the current maximum.
  • The answer after the i-th removal is the maximum before removeQueries[i] is added back.

My Attempts
#

VersionProblem
Two TLEsRight idea, but each step recomputed max(group_sum.values()) over all segments, O(n²) overall; the first find also lacked path compression
ACSwitched to arrays and kept the maximum in a variable
WAA different approach: sorted removed positions + prefix sums + a heap with lazy deletion. But popping from the heap did not decrement the deletion count, so deleting one segment discarded every segment with the same sum. For nums = [3, 1, 3], removeQueries = [1, 2, 0] the answer is [3, 3, 0]; it returned [3, 0, 0]
ACAdded the decrement (but list.insert is O(n), 1.3 s)

Solution
#

class Solution:
    def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:
        n = len(nums)
        parent = list(range(n))
        total = [0] * n
        alive = [False] * n

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        res, best = [], 0
        for i in reversed(removeQueries):
            res.append(best)                       # the answer before i is added back
            alive[i] = True
            total[i] = nums[i]
            for j in (i - 1, i + 1):
                if 0 <= j < n and alive[j]:
                    rj, ri = find(j), find(i)
                    parent[rj] = ri
                    total[ri] += total[rj]
            best = max(best, total[find(i)])
        return res[::-1]

Complexity
#

Time O(n · α(n)), space O(n).

Mistakes to Avoid
#

  • Do not recompute the maximum over all sets each step.
  • With lazy deletion, decrement the matching count whenever one is popped.
  • Record the answer before adding back, and reverse at the end.

Interview Explanation
#

Removal splits segments and Union-Find cannot split, so I add elements back in reverse, merging with existing neighbors and storing sums at the root. All numbers are positive, so the maximum only grows and a single variable holds it. The maximum before each addition is the answer for that removal, reversed at the end. Time O(n α(n)).

Related

LeetCode 2106: Maximum Fruits Harvested After at Most K Steps
·2 mins
LeetCode Hard Sliding-Window Prefix-Sum Binary-Search Array
LeetCode 2106 note: the harvest is always a contiguous block of fruits; covering [L, R] takes (R - L) + min(|start - L|, |R - start|) steps, so slide a window over the fruits array
LeetCode 220: Contains Duplicate III
·3 mins
LeetCode Hard Sliding-Window Bucket-Sort Ordered-Set Sorting Array
LeetCode 220 note: with bucket size valueDiff + 1, two numbers in one bucket always qualify, so only the two neighboring buckets need checking; the window keeps the latest indexDiff numbers, so each bucket holds at most one
LeetCode 2709: Greatest Common Divisor Traversal
·3 mins
LeetCode Hard Math Number-Theory Union-Find Sieve Gcd Array
LeetCode 2709 note: every pair of indices connects ⇔ one component; factor with SPF and union each number with its prime factors in Union-Find, treating 1 specially
LeetCode 952: Largest Component Size by Common Factor
·2 mins
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
LeetCode 952 note: sharing a factor ⇔ sharing a prime factor; factor each number and union indices with the same prime factor using Union-Find, with no pairwise GCDs
LeetCode 2302: Count Subarrays With Score Less Than K
·2 mins
LeetCode Hard Sliding-Window Prefix-Sum Binary-Search Array
LeetCode 2302 note: score = sum × length with positive numbers grows with the window; shrink while the score is >= k, and right - left + 1 valid subarrays end at right
LeetCode 2968: Apply Operations to Maximize Frequency Score
·2 mins
LeetCode Hard Sliding-Window Sorting Prefix-Sum Binary-Search Array
LeetCode 2968 note: after sorting, the cheapest common target for a block is its median; prefix sums give the cost in O(1), and it grows with the window, so slide