#2382

Maximum Segment Sum After Removals

Hard
ArrayUnion-FindPrefix SumOrdered SetUnion-FindDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n α(n))
Space
O(1)
O(n)
💡

Intuition

Time O(n α(n))Space O(n)

The optimal solution leverages a Union-Find (Disjoint Set Union) data structure to efficiently manage segments as elements are removed. This allows us to dynamically merge segments and compute their sums without recalculating everything from scratch.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a Union-Find structure to manage segments and an array to store segment sums.
  2. 2Step 2: For each removal index in removeQueries, mark the element as removed and check its neighboring elements to merge segments if they are still present.
  3. 3Step 3: Update the segment sums accordingly and track the maximum segment sum after each removal.
solution.py38 lines
1class UnionFind:
2    def __init__(self, n):
3        self.parent = list(range(n))
4        self.size = [1] * n
5        self.sum = [0] * n
6    def find(self, x):
7        if self.parent[x] != x:
8            self.parent[x] = self.find(self.parent[x])
9        return self.parent[x]
10    def union(self, x, y):
11        rootX = self.find(x)
12        rootY = self.find(y)
13        if rootX != rootY:
14            if self.size[rootX] < self.size[rootY]:
15                rootX, rootY = rootY, rootX
16            self.parent[rootY] = rootX
17            self.size[rootX] += self.size[rootY]
18            self.sum[rootX] += self.sum[rootY]
19    def add(self, idx, value):
20        self.sum[idx] = value
21
22
23def maxSegmentSum(nums, removeQueries):
24    n = len(nums)
25    uf = UnionFind(n)
26    for i in range(n):
27        uf.add(i, nums[i])
28    answer = []
29    max_sum = sum(nums)
30    for idx in removeQueries:
31        uf.add(idx, 0)
32        if idx > 0 and nums[idx - 1] != 0:
33            uf.union(idx, idx - 1)
34        if idx < n - 1 and nums[idx + 1] != 0:
35            uf.union(idx, idx + 1)
36        max_sum = max(max_sum, max(uf.sum))
37        answer.append(max_sum)
38    return answer

Complexity note: The time complexity is efficient due to the union-find operations, which are nearly constant time due to path compression and union by size. The space complexity is O(n) because we store additional arrays for parent, size, and sum.

  • 1Using Union-Find helps manage segments efficiently.
  • 2Dynamic updates to segment sums reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.