- 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
- 39 lines of Python from the credited upstream file 3344.py.
- The implementation keeps its working state in language-native values and containers.
- 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.
1class Solution:2 def maxSizedArray(self, s: int) -> int:3 def getNumbersWithBitSet(n: int, i: int) -> int:4 """5 Returns the number of integers in [0, n - 1] with the i-th bit set.6 7 For the i-th bit, numbers in the range [0, n - 1] can be divided into8 groups of 2^(i + 1) numbers. In each group, exactly half of the numbers9 have the i-th bit set.10 """11 groupSize = 1 << (i + 1)12 halfGroupSize = 1 << i13 fullGroups = n groupSize14 remaining = max(0, (n % groupSize) - halfGroupSize)15 return fullGroups * halfGroupSize + remaining16 17 def getArraySum(n: int) -> int:18 """19 Returns the sum of all i * (j OR k) values in 3D arrays of size n^3.20 21 sum(i * (j OR k)), where 0 <= i, j, k < n22 = 0 * (j OR k) + 1 * (j OR k) + ... + (n - 1) * (j OR k)23 = (0 + 1 + ... + n - 1) * sum(j OR k)24 = (n * (n - 1) / 2) * sum(j OR k)25 """26 arithmeticSum = n * (n - 1) 2 27 orSum = 0 28 for i in range(n.bit_length()):29 numbersWithoutBit = n - getNumbersWithBitSet(n, i)30 pairsWithBit = n**2 - numbersWithoutBit**231 orSum += pairsWithBit * (1 << i) 32 return arithmeticSum * orSum33 34 if s == 0:35 return 136 l = 037 r = 1196 38 return bisect.bisect_right(range(l, r + 1), s, key=getArraySum) - 1 + l39