Talentd
FleetCode
Make and follow sheets.Sign in

Maximize Alternating Sum Using Swaps solution and explanation

HardArrayGreedySortingUnion Find4 min read62.5% acceptanceUpdated 24 Mar 2026
Leetcode 3695 | Maximize Alternating Sum Using Swaps Detailed Solution | Biweekly 166Q4 | DSUSamrat Bhardwaj · 27:37 · 466 viewsWatch on YouTube
5 more videos on this problem
  1. Leetcode 3695 | Maximize Alternating Sum Using Swaps Detailed Solution | Biweekly 166Q4 | DSUSamrat Bhardwaj · 27:37 · 466 views
  2. Maximize Alternating Sum Using Swaps | LeetCode 3695 | Biweekly Contest 166Sanyam IIT Guwahati · 15:53 · 453 views
  3. 3695. Maximize Alternating Sum Using Swaps (Leetcode Hard)Programming Live with Larry · 11:53 · 156 views
  4. [English] 3695. Maximize Alternating Sum Using Swaps [Leetcode Hard]Romain Lhotte · 13:35 · 142 views
  5. Leetcode 3695 | Maximize Alternating Sum Using SwapsCodeWithMeGuys · 15:16 · 133 views
  6. Maximize Alternating Sum Using Swaps LeetCode 3695Karan · 8:46 · 31 views

The problem

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] = [pi, qi]. For each pair [pi, qi] in swaps, you are allowed to swap the elements at indices pi and qi. 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 <= 105
  • 1 <= nums[i] <= 109
  • 0 <= swaps.length <= 105
  • swaps[i] = [pi, qi]
  • 0 <= pi < qi <= nums.length - 1
  • [pi, qi] != [pj, qj]

Approach overview

Problem Overview: You are given an array where swaps are allowed between certain indices. After performing any number of valid swaps, compute the maximum possible alternating sum of the array, defined as a[0] - a[1] + a[2] - a[3] .... The challenge is that swaps are restricted, so you cannot arbitrarily reorder the entire array.

Approach 1: Brute Force Swap Exploration (Exponential time, O(n!) time, O(n) space)

A naive approach tries all permutations reachable through swaps and computes the alternating sum for each arrangement. For every configuration, iterate through the array and evaluate a[0] - a[1] + a[2] .... The maximum value across all reachable permutations is the answer. This approach becomes infeasible quickly because the number of possible permutations grows factorially. It only works for very small arrays and mainly demonstrates the core objective of maximizing positive positions and minimizing negative ones.

Approach 2: Union-Find + Greedy Assignment (Sorting Based) (O(n log n) time, O(n) space)

The key observation: if swaps are allowed between indices, those indices form connected components. Within each component, values can be freely rearranged. Use Union Find to group indices into components. For each component, collect its indices and the values currently stored there.

Next, determine how each index contributes to the alternating sum. Even indices contribute positively, odd indices contribute negatively. Inside a component, sort the values and greedily assign them: place the largest values at even indices (positive contribution) and the smallest values at odd indices (negative contribution). This local greedy strategy maximizes the contribution of each component independently. Sorting inside each component gives O(k log k) work per component, leading to O(n log n) overall.

This method combines greedy reasoning with connectivity grouping from union find. The array itself is only reorganized within components, and sorting ensures optimal assignment for alternating positions.

Recommended for interviews: The Union-Find + Greedy approach is the expected solution. Interviewers want to see that you model swap constraints as connected components, then reduce the problem to a local rearrangement problem. Mentioning the brute-force idea shows you understand the objective, but identifying components and greedily assigning values demonstrates strong algorithmic reasoning with sorting and connectivity structures.

The written solution for this problem is still being prepared. Try it yourself in the meantime.

Try solving it yourself

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force PermutationsO(n!)O(n)Only for very small arrays or conceptual understanding
Union-Find + Greedy with SortingO(n log n)O(n)General optimal solution when swaps create connected components
Component Heap AssignmentO(n log n)O(n)Useful when streaming values or assigning greedily with priority queues

Frequently asked questions

Is Maximize Alternating Sum Using Swaps easy or hard?

Maximize Alternating Sum Using Swaps is typically classified as a Hard problem because it combines multiple concepts: Union Find for connectivity, greedy reasoning for maximizing contributions, and sorting within components. Recognizing that swaps form independent components is the main insight.

Maximize Alternating Sum Using Swaps Python/Java solution

Implement Union Find to group swappable indices, collect values for each component, sort them, and greedily assign them to maximize the alternating sum. The same logic works across Python, Java, C++, and Go with O(n log n) complexity and O(n) additional space.

How to solve Maximize Alternating Sum Using Swaps in O(n log n)?

First build connected components using Union Find based on the allowed swaps. For each component, gather its indices and corresponding values. Sort the values and assign the largest numbers to indices with positive contribution (even positions) and smaller numbers to negative positions (odd indices). This greedy placement maximizes the alternating sum.

What is the best approach for Maximize Alternating Sum Using Swaps?

The most effective solution uses Union Find to group indices that can be swapped and then applies a greedy assignment within each component. Values in the component are sorted and distributed so that the largest numbers occupy even indices (positive contribution) and the smallest occupy odd indices (negative contribution). This achieves the optimal alternating sum in O(n log n) time.

Is Maximize Alternating Sum Using Swaps asked at Google/Amazon/Meta?

Problems combining swap constraints with Union Find and greedy assignment frequently appear in interviews at companies like Amazon and Google. Variants that require grouping indices and rearranging values within components are common in high-difficulty array and graph problems.

What data structure is used in Maximize Alternating Sum Using Swaps?

The primary data structure is Union Find (Disjoint Set Union) to identify groups of indices that can be freely swapped. Arrays and sorting are then used to reorder values inside each component, while greedy logic determines placement for alternating sum optimization.

What is the time complexity of Maximize Alternating Sum Using Swaps?

The optimal solution runs in O(n log n) time. Union-Find operations for building components take nearly O(n) with path compression, while sorting values inside each component dominates the complexity. Space complexity is O(n) for storing components and temporary arrays.

Comments

Now write it yourselfClose this page and solve Maximize Alternating Sum Using Swaps in the editor, without looking.
Practise Maximize Alternating Sum Using Swaps