#3695
Maximize Alternating Sum Using Swaps
HardArrayGreedyUnion-FindSortingGraph TheorySortingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Use a Disjoint Set Union (DSU) to group indices that can be swapped. For each group, sort the values and place the largest in even indices to maximize the alternating sum.
⚙️
Algorithm
3 steps- 1Step 1: Build connected components using DSU based on the swaps.
- 2Step 2: For each component, collect values and sort them in descending order.
- 3Step 3: Assign the largest values to even indices and the rest to odd indices to maximize the alternating sum.
solution.py25 lines
1class DSU:
2 def __init__(self, n):
3 self.parent = list(range(n))
4 def find(self, x):
5 if self.parent[x] != x:
6 self.parent[x] = self.find(self.parent[x])
7 return self.parent[x]
8 def union(self, x, y):
9 self.parent[self.find(x)] = self.find(y)
10
11def maxAlternatingSum(nums, swaps):
12 dsu = DSU(len(nums))
13 for p, q in swaps:
14 dsu.union(p, q)
15 components = {}
16 for i in range(len(nums)):
17 root = dsu.find(i)
18 if root not in components:
19 components[root] = []
20 components[root].append(nums[i])
21 total_sum = 0
22 for comp in components.values():
23 comp.sort(reverse=True)
24 total_sum += sum(comp[i] if i % 2 == 0 else -comp[i] for i in range(len(comp)))
25 return total_sumℹ
Complexity note: DSU operations are nearly constant time, and sorting the components takes linearithmic time.
- 1Swaps create connected components.
- 2Maximize even indices with the largest values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.