- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 59 lines of Python from the credited upstream file maximum-points-activated-with-one-addition.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maxActivated(self, points):7 """8 :type points: List[List[int]]9 :rtype: int10 """11 class UnionFind(object): 12 def __init__(self, n):13 self.set = range(n)14 self.rank = [0]*n15 self.size = [1]*n16 17 def find_set(self, x):18 stk = []19 while self.set[x] != x: 20 stk.append(x)21 x = self.set[x]22 while stk:23 self.set[stk.pop()] = x24 return x25 26 def union_set(self, x, y):27 x, y = self.find_set(x), self.find_set(y)28 if x == y:29 return False30 if self.rank[x] > self.rank[y]: 31 x, y = y, x32 elif self.rank[x] == self.rank[y]:33 self.rank[y] += 134 self.set[x] = self.set[y]35 self.size[y] += self.size[x]36 return True37 38 def total(self, x):39 return self.size[self.find_set(x)]40 41 N_DIM, N_ADD = 2, 142 uf = UnionFind(len(points))43 lookup = [{} for _ in xrange(N_DIM)]44 for i, p in enumerate(points):45 for j in xrange(len(lookup)):46 if p[j] in lookup[j]:47 uf.union_set(i, lookup[j][p[j]])48 else:49 lookup[j][p[j]] = i50 top = [0]*min(N_ADD+1, len(points))51 for i in xrange(len(points)):52 if uf.find_set(i) != i:53 continue54 s = uf.total(i)55 for j in xrange(len(top)):56 if s > top[j]:57 top[j], s = s,top[j]58 return sum(top)+N_ADD59