- 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
- 62 lines of Python from the credited upstream file maximize-points-after-choosing-k-tasks.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 maxPoints(self, technique1, technique2, k):10 """11 :type technique1: List[int]12 :type technique2: List[int]13 :type k: int14 :rtype: int15 """16 def nth_element(nums, n, left=0, compare=lambda a, b: a < b):17 def tri_partition(nums, left, right, target, compare):18 mid = left19 while mid <= right:20 if nums[mid] == target:21 mid += 122 elif compare(nums[mid], target):23 nums[left], nums[mid] = nums[mid], nums[left]24 left += 125 mid += 126 else:27 nums[mid], nums[right] = nums[right], nums[mid]28 right -= 129 return left, right30 31 right = len(nums)-132 while left <= right:33 pivot_idx = random.randint(left, right)34 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)35 if pivot_left <= n <= pivot_right:36 return37 elif pivot_left > n:38 right = pivot_left-139 else: 40 left = pivot_right+141 42 idxs = range(len(technique1))43 if k != len(technique1):44 nth_element(idxs, k-1, compare=lambda a, b: technique1[a]-technique2[a] > technique1[b]-technique2[b])45 return sum(technique1[idxs[i]] if i < k else max(technique1[idxs[i]], technique2[idxs[i]]) for i in xrange(len(technique1)))46 47 48495051class Solution2(object):52 def maxPoints(self, technique1, technique2, k):53 """54 :type technique1: List[int]55 :type technique2: List[int]56 :type k: int57 :rtype: int58 """59 idxs = range(len(technique1))60 idxs.sort(key=lambda i: technique1[i]-technique2[i], reverse=True)61 return sum(technique1[idxs[i]] if i < k else max(technique1[idxs[i]], technique2[idxs[i]]) for i in xrange(len(technique1)))62