- 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
- 79 lines of Python from the credited upstream file maximum-bitwise-and-after-increment-operations.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 maximumAND(self, nums, k, m):10 """11 :type nums: List[int]12 :type k: int13 :type m: 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 result = 043 for i in reversed(xrange((max(nums)+k).bit_length())):44 target = result|(1<<i)45 costs = []46 for x in nums:47 l = (target&~x).bit_length()48 mask = (1<<l)-149 costs.append((target&mask)-(x&mask))50 nth_element(costs, m-1)51 if sum(costs[i] for i in xrange(m)) <= k:52 result |= 1<<i53 return result54 55 56575859class Solution2(object):60 def maximumAND(self, nums, k, m):61 """62 :type nums: List[int]63 :type k: int64 :type m: int65 :rtype: int66 """67 result = 068 for i in reversed(xrange((max(nums)+k).bit_length())):69 target = result|(1<<i)70 costs = []71 for x in nums:72 l = (target&~x).bit_length()73 mask = (1<<l)-174 costs.append((target&mask)-(x&mask))75 costs.sort()76 if sum(costs[i] for i in xrange(m)) <= k:77 result |= 1<<i78 return result79