- 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
- 60 lines of Python from the credited upstream file absolute-difference-between-maximum-and-minimum-k-elements.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 absDifference(self, nums, k):10 """11 :type nums: List[int]12 :type k: int13 :rtype: int14 """15 def nth_element(nums, n, left=0, 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 right = 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 nth_element(nums, k-1)42 total1 = sum(nums[i] for i in xrange(k))43 nth_element(nums, k-1, compare=lambda a, b: a > b)44 total2 = sum(nums[i] for i in xrange(k))45 return abs(total1-total2)46 47 48495051class Solution2(object):52 def absDifference(self, nums, k):53 """54 :type nums: List[int]55 :type k: int56 :rtype: int57 """58 nums.sort()59 return abs(sum(nums[i] for i in xrange(k))-sum(nums[~i] for i in xrange(k)))60