#3630

Partition Array for Maximum XOR and AND

Hard
ArrayMathGreedyBit ManipulationEnumerationBit ManipulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

By fixing B and calculating the XOR of the remaining elements, we can efficiently compute the maximum possible sum without checking all subsets.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total XOR of all elements in nums.
  2. 2Step 2: Iterate through each element, treating it as part of B, and compute AND for B and XOR for A and C.
  3. 3Step 3: Keep track of the maximum sum encountered.
solution.py10 lines
1def maxPartition(nums):
2    total_xor = 0
3    for num in nums:
4        total_xor ^= num
5    max_sum = 0
6    for num in nums:
7        andB = num
8        xorA = total_xor ^ num
9        max_sum = max(max_sum, andB + xorA)
10    return max_sum

Complexity note: We compute total XOR in O(n) and iterate through nums once, resulting in O(n) overall complexity.

  • 1XOR is maximized by including high-value bits.
  • 2AND is maximized by including elements with common bits.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.