Approach
Breadth-first search
For Maximize Alternating Sum Using Swaps, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 70 lines of Python from the credited upstream file maximize-alternating-sum-using-swaps.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import random5 6 78class Solution(object):9 def maxAlternatingSum(self, nums, swaps):10 """11 :type nums: List[int]12 :type swaps: List[List[int]]13 :rtype: int14 """15 def nth_element(nums, n, compare=lambda a, b: a < b):16 def tri_partition(nums, left, right, target, compare):17 mid = left18 while mid <= right:19 if nums[mid] == target:20 mid += 121 elif compare(nums[mid], target):22 nums[left], nums[mid] = nums[mid], nums[left]23 left += 124 mid += 125 else:26 nums[mid], nums[right] = nums[right], nums[mid]27 right -= 128 return left, right29 30 left, right = 0, len(nums)-131 while left <= right:32 pivot_idx = random.randint(left, right)33 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)34 if pivot_left <= n <= pivot_right:35 return36 elif pivot_left > n:37 right = pivot_left-138 else: 39 left = pivot_right+140 41 def bfs(u):42 q = []43 if lookup[u]:44 return q45 lookup[u] = True46 q.append(u)47 for u in q:48 for v in adj[u]:49 if lookup[v]:50 continue51 lookup[v] = True52 q.append(v)53 return q54 55 adj = [[] for _ in xrange(len(nums))]56 for i, j in swaps:57 adj[i].append(j)58 adj[j].append(i)59 lookup = [False]*len(adj)60 result = sum(nums)61 for u in xrange(len(nums)):62 g = bfs(u)63 if not g:64 continue65 l = sum(i%2 for i in g)66 arr = [nums[i] for i in g]67 nth_element(arr, l)68 result -= 2*sum(arr[i] for i in xrange(l))69 return result70