- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 85 lines of Python from the credited upstream file partition-array-for-maximum-xor-and-and.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maximizeXorAndXor(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 def max_xor_subset(nums): 12 base = [0]*l 13 for x in nums: 14 for i in reversed(xrange(len(base))):15 if not x&(1<<i):16 continue17 if base[i] == 0:18 base[i] = x19 break20 x ^= base[i]21 max_xor = 022 for b in reversed(base): 23 if (max_xor^b) > max_xor:24 max_xor ^= b25 return max_xor26 27 l = max(nums).bit_length()28 n = len(nums)29 and_arr = [0]*(1<<n)30 xor_arr = [0]*(1<<n)31 for mask in xrange(1, 1<<n):32 lb = mask&-mask33 i = lb.bit_length()-134 and_arr[mask] = and_arr[mask^lb]&nums[i] if mask^lb else nums[i]35 xor_arr[mask] = xor_arr[mask^lb]^nums[i]36 result = 037 full_mask = (1<<n)-138 for mask in xrange(1, 1<<n):39 total_and = and_arr[mask]40 total_xor = xor_arr[full_mask^mask]41 max_xor = max_xor_subset(((nums[i]&~total_xor) for i in xrange(n) if not (mask&(1<<i))))42 result = max(result, total_and+total_xor+2*max_xor)43 return result44 45 46474849class Solution2(object):50 def maximizeXorAndXor(self, nums):51 """52 :type nums: List[int]53 :rtype: int54 """55 def max_xor_subset(nums): 56 base = [0]*l 57 for x in nums: 58 for i in reversed(xrange(len(base))):59 if not x&(1<<i):60 continue61 if base[i] == 0:62 base[i] = x63 break64 x ^= base[i]65 max_xor = 066 for b in reversed(base): 67 if (max_xor^b) > max_xor:68 max_xor ^= b69 return max_xor70 71 l = max(nums).bit_length()72 n = len(nums)73 result = 074 for mask in xrange(1, 1<<n):75 and_arr = -176 xor_arr = 077 for i in xrange(n):78 if mask&(1<<i):79 and_arr = and_arr&nums[i] if and_arr != -1 else nums[i]80 else:81 xor_arr ^= nums[i]82 max_xor = max_xor_subset(((nums[i]&~xor_arr) for i in xrange(n) if not (mask&(1<<i))))83 result = max(result, and_arr+xor_arr+2*max_xor)84 return result85