- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 56 lines of Python from the credited upstream file maximum-alternating-sum-of-squares.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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):10 """11 :type nums: List[int]12 :rtype: int13 """14 def nth_element(nums, n, left=0, compare=lambda a, b: a < b):15 def tri_partition(nums, left, right, target, compare):16 mid = left17 while mid <= right:18 if nums[mid] == target:19 mid += 120 elif compare(nums[mid], target):21 nums[left], nums[mid] = nums[mid], nums[left]22 left += 123 mid += 124 else:25 nums[mid], nums[right] = nums[right], nums[mid]26 right -= 127 return left, right28 29 right = len(nums)-130 while left <= right:31 pivot_idx = random.randint(left, right)32 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)33 if pivot_left <= n <= pivot_right:34 return35 elif pivot_left > n:36 right = pivot_left-137 else: 38 left = pivot_right+139 40 arr = [x**2 for x in nums]41 nth_element(arr, len(nums)2)42 return sum(arr)-2*sum(arr[i] for i in xrange(len(arr)2))43 44 45464748class Solution2(object):49 def maxAlternatingSum(self, nums):50 """51 :type nums: List[int]52 :rtype: int53 """54 arr = sorted(x**2 for x in nums)55 return sum(arr)-2*sum(arr[i] for i in xrange(len(arr)2))56