- 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
- 52 lines of Python from the credited upstream file maximize-ysum-by-picking-a-triplet-of-distinct-xvalues.py.
- The implementation visibly relies on sequence storage, hash lookup.
- 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 collections5import itertools6import random7 8 910class Solution(object):11 def maxSumDistinctTriplet(self, x, y):12 """13 :type x: List[int]14 :type y: List[int]15 :rtype: int16 """17 def nth_element(nums, n, left=0, compare=lambda a, b: a < b):18 def tri_partition(nums, left, right, target, compare):19 mid = left20 while mid <= right:21 if nums[mid] == target:22 mid += 123 elif compare(nums[mid], target):24 nums[left], nums[mid] = nums[mid], nums[left]25 left += 126 mid += 127 else:28 nums[mid], nums[right] = nums[right], nums[mid]29 right -= 130 return left, right31 32 right = len(nums)-133 while left <= right:34 pivot_idx = random.randint(left, right)35 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)36 if pivot_left <= n <= pivot_right:37 return38 elif pivot_left > n:39 right = pivot_left-140 else: 41 left = pivot_right+142 43 K = 344 lookup = collections.defaultdict(int)45 for i, j in itertools.izip(x, y):46 lookup[i] = max(lookup[i], j)47 if len(lookup) < K:48 return -149 vals = lookup.values()50 nth_element(vals, K-1, compare=lambda x, y: x > y)51 return sum(vals[i] for i in xrange(K))52