Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
nums[0] and nums[2]. nums is now [3, 2, 1].nums[1] and nums[2]. nums is now [3, 1, 2].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 <= 1051 <= nums[i] <= 1090 <= swaps.length <= 105swaps[i] = [pi, qi]0 <= pi < qi <= nums.length - 1[pi, qi] != [pj, qj]Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy · Union-Find
[1,2,3] [[0,2],[1,2]]
[1,2,3] [[1,2]]
[1,1000000000,1,1000000000,1,1000000000] []
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
//
// // 模板来源 https://leetcode.cn/circle/discuss/mOr1u6/
// type unionFind struct {
// fa []int // 代表元
// odd []int // 集合中的奇数个数
// }
//
// func newUnionFind(n int) unionFind {
// fa := make([]int, n)
// odd := make([]int, n)
// // 一开始有 n 个集合 {0}, {1}, ..., {n-1}
// // 集合 i 的代表元是自己
// for i := range fa {
// fa[i] = i
// odd[i] = i % 2
// }
// return unionFind{fa, odd}
// }
//
// // 返回 x 所在集合的代表元
// // 同时做路径压缩,也就是把 x 所在集合中的所有元素的 fa 都改成代表元
// func (u unionFind) find(x int) int {
// // 如果 fa[x] == x,则表示 x 是代表元
// if u.fa[x] != x {
// u.fa[x] = u.find(u.fa[x]) // fa 改成代表元
// }
// return u.fa[x]
// }
//
// // 把 from 所在集合合并到 to 所在集合中
// func (u *unionFind) merge(from, to int) {
// x, y := u.find(from), u.find(to)
// if x == y { // from 和 to 在同一个集合,不做合并
// return
// }
// u.fa[x] = y // 合并集合
// u.odd[y] += u.odd[x] // 更新集合中的奇数个数
// }
//
// func maxAlternatingSum(nums []int, swaps [][]int) (ans int64) {
// n := len(nums)
// uf := newUnionFind(n)
// for _, p := range swaps {
// uf.merge(p[0], p[1])
// }
//
// g := make([][]int, n)
// for i, x := range nums {
// f := uf.find(i)
// g[f] = append(g[f], x) // 相同集合的元素分到同一组
// }
//
// for i, a := range g {
// if a == nil {
// continue
// }
// slices.Sort(a)
// odd := uf.odd[i]
// // 小的取负号,大的取正号
// for j, x := range a {
// if j < odd {
// ans -= int64(x)
// } else {
// ans += int64(x)
// }
// }
// }
// return
// }
// Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
package main
import "slices"
// https://space.bilibili.com/206214
// 模板来源 https://leetcode.cn/circle/discuss/mOr1u6/
type unionFind struct {
fa []int // 代表元
odd []int // 集合中的奇数个数
}
func newUnionFind(n int) unionFind {
fa := make([]int, n)
odd := make([]int, n)
// 一开始有 n 个集合 {0}, {1}, ..., {n-1}
// 集合 i 的代表元是自己
for i := range fa {
fa[i] = i
odd[i] = i % 2
}
return unionFind{fa, odd}
}
// 返回 x 所在集合的代表元
// 同时做路径压缩,也就是把 x 所在集合中的所有元素的 fa 都改成代表元
func (u unionFind) find(x int) int {
// 如果 fa[x] == x,则表示 x 是代表元
if u.fa[x] != x {
u.fa[x] = u.find(u.fa[x]) // fa 改成代表元
}
return u.fa[x]
}
// 把 from 所在集合合并到 to 所在集合中
func (u *unionFind) merge(from, to int) {
x, y := u.find(from), u.find(to)
if x == y { // from 和 to 在同一个集合,不做合并
return
}
u.fa[x] = y // 合并集合
u.odd[y] += u.odd[x] // 更新集合中的奇数个数
}
func maxAlternatingSum(nums []int, swaps [][]int) (ans int64) {
n := len(nums)
uf := newUnionFind(n)
for _, p := range swaps {
uf.merge(p[0], p[1])
}
g := make([][]int, n)
for i, x := range nums {
f := uf.find(i)
g[f] = append(g[f], x) // 相同集合的元素分到同一组
}
for i, a := range g {
if a == nil {
continue
}
slices.Sort(a)
odd := uf.odd[i]
// 小的取负号,大的取正号
for j, x := range a {
if j < odd {
ans -= int64(x)
} else {
ans += int64(x)
}
}
}
return
}
# Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
#
# @lc app=leetcode id=3695 lang=python3
#
# [3695] Maximize Alternating Sum Using Swaps
#
# @lc code=start
class Solution:
def maxAlternatingSum(self, nums: List[int], swaps: List[List[int]]) -> int:
n = len(nums)
adj = [[] for _ in range(n)]
for u, v in swaps:
adj[u].append(v)
adj[v].append(u)
visited = [False] * n
total_sum = 0
for i in range(n):
if not visited[i]:
# Start a traversal to find the connected component
component_indices = []
stack = [i]
visited[i] = True
while stack:
u = stack.pop()
component_indices.append(u)
for v in adj[u]:
if not visited[v]:
visited[v] = True
stack.append(v)
# Collect values and count even/odd positions in this component
values = []
even_slots = 0
odd_slots = 0
for idx in component_indices:
values.append(nums[idx])
if idx % 2 == 0:
even_slots += 1
else:
odd_slots += 1
# Sort values descending
values.sort(reverse=True)
# Assign largest values to even slots (positive contribution)
# Assign smallest values to odd slots (negative contribution)
# The first even_slots values are added
for k in range(even_slots):
total_sum += values[k]
# The remaining odd_slots values are subtracted
for k in range(even_slots, len(values)):
total_sum -= values[k]
return total_sum
# @lc code=end
// Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
//
// // 模板来源 https://leetcode.cn/circle/discuss/mOr1u6/
// type unionFind struct {
// fa []int // 代表元
// odd []int // 集合中的奇数个数
// }
//
// func newUnionFind(n int) unionFind {
// fa := make([]int, n)
// odd := make([]int, n)
// // 一开始有 n 个集合 {0}, {1}, ..., {n-1}
// // 集合 i 的代表元是自己
// for i := range fa {
// fa[i] = i
// odd[i] = i % 2
// }
// return unionFind{fa, odd}
// }
//
// // 返回 x 所在集合的代表元
// // 同时做路径压缩,也就是把 x 所在集合中的所有元素的 fa 都改成代表元
// func (u unionFind) find(x int) int {
// // 如果 fa[x] == x,则表示 x 是代表元
// if u.fa[x] != x {
// u.fa[x] = u.find(u.fa[x]) // fa 改成代表元
// }
// return u.fa[x]
// }
//
// // 把 from 所在集合合并到 to 所在集合中
// func (u *unionFind) merge(from, to int) {
// x, y := u.find(from), u.find(to)
// if x == y { // from 和 to 在同一个集合,不做合并
// return
// }
// u.fa[x] = y // 合并集合
// u.odd[y] += u.odd[x] // 更新集合中的奇数个数
// }
//
// func maxAlternatingSum(nums []int, swaps [][]int) (ans int64) {
// n := len(nums)
// uf := newUnionFind(n)
// for _, p := range swaps {
// uf.merge(p[0], p[1])
// }
//
// g := make([][]int, n)
// for i, x := range nums {
// f := uf.find(i)
// g[f] = append(g[f], x) // 相同集合的元素分到同一组
// }
//
// for i, a := range g {
// if a == nil {
// continue
// }
// slices.Sort(a)
// odd := uf.odd[i]
// // 小的取负号,大的取正号
// for j, x := range a {
// if j < odd {
// ans -= int64(x)
// } else {
// ans += int64(x)
// }
// }
// }
// return
// }
// Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3695: Maximize Alternating Sum Using Swaps
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
//
// // 模板来源 https://leetcode.cn/circle/discuss/mOr1u6/
// type unionFind struct {
// fa []int // 代表元
// odd []int // 集合中的奇数个数
// }
//
// func newUnionFind(n int) unionFind {
// fa := make([]int, n)
// odd := make([]int, n)
// // 一开始有 n 个集合 {0}, {1}, ..., {n-1}
// // 集合 i 的代表元是自己
// for i := range fa {
// fa[i] = i
// odd[i] = i % 2
// }
// return unionFind{fa, odd}
// }
//
// // 返回 x 所在集合的代表元
// // 同时做路径压缩,也就是把 x 所在集合中的所有元素的 fa 都改成代表元
// func (u unionFind) find(x int) int {
// // 如果 fa[x] == x,则表示 x 是代表元
// if u.fa[x] != x {
// u.fa[x] = u.find(u.fa[x]) // fa 改成代表元
// }
// return u.fa[x]
// }
//
// // 把 from 所在集合合并到 to 所在集合中
// func (u *unionFind) merge(from, to int) {
// x, y := u.find(from), u.find(to)
// if x == y { // from 和 to 在同一个集合,不做合并
// return
// }
// u.fa[x] = y // 合并集合
// u.odd[y] += u.odd[x] // 更新集合中的奇数个数
// }
//
// func maxAlternatingSum(nums []int, swaps [][]int) (ans int64) {
// n := len(nums)
// uf := newUnionFind(n)
// for _, p := range swaps {
// uf.merge(p[0], p[1])
// }
//
// g := make([][]int, n)
// for i, x := range nums {
// f := uf.find(i)
// g[f] = append(g[f], x) // 相同集合的元素分到同一组
// }
//
// for i, a := range g {
// if a == nil {
// continue
// }
// slices.Sort(a)
// odd := uf.odd[i]
// // 小的取负号,大的取正号
// for j, x := range a {
// if j < odd {
// ans -= int64(x)
// } else {
// ans += int64(x)
// }
// }
// }
// return
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.