Problem solution · Python

Maximize Alternating Sum Using Swaps

Maximize Alternating Sum Using Swaps: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
70 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMaximize Alternating Sum Using Swaps · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n + s)# Space: O(n + s) import random  # bfs, flood fill, quick selectclass Solution(object):    def maxAlternatingSum(self, nums, swaps):        """        :type nums: List[int]        :type swaps: List[List[int]]        :rtype: int        """        def nth_element(nums, n, compare=lambda a, b: a < b):            def tri_partition(nums, left, right, target, compare):                mid = left                while mid <= right:                    if nums[mid] == target:                        mid += 1                    elif compare(nums[mid], target):                        nums[left], nums[mid] = nums[mid], nums[left]                        left += 1                        mid += 1                    else:                        nums[mid], nums[right] = nums[right], nums[mid]                        right -= 1                return left, right             left, right = 0, len(nums)-1            while left <= right:                pivot_idx = random.randint(left, right)                pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)                if pivot_left <= n <= pivot_right:                    return                elif pivot_left > n:                    right = pivot_left-1                else:  # pivot_right < n.                    left = pivot_right+1         def bfs(u):            q = []            if lookup[u]:                return q            lookup[u] = True            q.append(u)            for u in q:                for v in adj[u]:                    if lookup[v]:                        continue                    lookup[v] = True                    q.append(v)            return q            adj = [[] for _ in xrange(len(nums))]        for i, j in swaps:            adj[i].append(j)            adj[j].append(i)        lookup = [False]*len(adj)        result = sum(nums)        for u in xrange(len(nums)):            g = bfs(u)            if not g:                continue            l = sum(i%2 for i in g)            arr = [nums[i] for i in g]            nth_element(arr, l)            result -= 2*sum(arr[i] for i in xrange(l))        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗