Maximize Alternating Sum Using Swaps Problem
Description
LeetCode Problem 3695.
You are given an integer array nums.
You want to maximize the alternating sum of nums, which is defined as the value obtained by adding elements at even indices and subtracting elements at odd indices. That is, nums[0] - nums[1] + nums[2] - nums[3]...
You are also given a 2D integer array swaps where swaps[i] = [p_i, q_i]. For each pair [p_i, q_i] in swaps, you are allowed to swap the elements at indices p_i and q_i. These swaps can be performed any number of times and in any order.
Return the maximum possible alternating sum of nums.
Example 1:
Input: nums = [1,2,3], swaps = [[0,2],[1,2]]
Output: 4
Explanation:
The maximum alternating sum is achieved when nums is [2, 1, 3] or [3, 1, 2]. As an example, you can obtain nums = [2, 1, 3] as follows.
- Swap nums[0] and nums[2]. nums is now [3, 2, 1].
- Swap nums[1] and nums[2]. nums is now [3, 1, 2].
- Swap nums[0] and nums[2]. nums is now [2, 1, 3].
Example 2:
Input: nums = [1,2,3], swaps = [[1,2]]
Output: 2
Explanation:
The maximum alternating sum is achieved by not performing any swaps.
Example 3:
Input: nums = [1,1000000000,1,1000000000,1,1000000000], swaps = []
Output: -2999999997
Explanation:
Since we cannot perform any swaps, the maximum alternating sum is achieved by not performing any swaps.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= swaps.length <= 10^5swaps[i] = [p_i, q_i]0 <= p_i < q_i <= nums.length - 1[p_i, q_i] != [p_j, q_j]
Solution
Approach: Union-Find + Sorting
Swaps can be applied any number of times and in any order, so the indices joined by swaps (directly or through a chain) form a connected component, and inside a component the values can be rearranged into any order. Components are independent of each other.
Use a union-find structure to build the components. In a component, let odd be the number of odd indices it contains. Those positions are subtracted, so the best choice is to put the odd smallest values on them and the remaining, larger values on the even indices, which are added. Sort the values of the component and add sum(vals[odd:]) - sum(vals[:odd]) to the answer.
Complexity: O((n + m) α(n) + n log n) time and O(n) space, where n is the length of nums and m is the number of swaps.
class Solution:
def maxAlternatingSum(self, nums: List[int], swaps: List[List[int]]) -> int:
n = len(nums)
p = list(range(n))
def find(x: int) -> int:
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
for a, b in swaps:
p[find(a)] = find(b)
groups = {}
for i in range(n):
groups.setdefault(find(i), []).append(i)
ans = 0
for idx in groups.values():
vals = sorted(nums[i] for i in idx)
even = sum(1 for i in idx if i % 2 == 0)
odd = len(idx) - even
ans += sum(vals[odd:]) - sum(vals[:odd])
return ans