LeetCode 2172: Maximum AND Sum of Array Solution

Master LeetCode problem 2172 (Maximum AND Sum of Array), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2172. Maximum AND Sum of Array

Problem Explanation

Explanation:

To maximize the AND sum, we need to strategically place the numbers into slots such that the bitwise AND operation between each number and its corresponding slot number contributes to the sum. We can achieve this by considering the binary representation of the numbers and the slot numbers.

  1. Iterate over all possible bit positions from the most significant bit to the least significant bit.
  2. For each bit position, count the number of set bits in the numbers that have a set bit at that position.
  3. Place the numbers with the most significant bits in the slots that correspond to the positions of the set bits.
  4. Repeat this process for each subsequent bit position until all numbers are placed in the slots.

By following this approach, we can maximize the AND sum of the array.

Time Complexity: O(n) Space Complexity: O(1)

:

Solution Code

class Solution {
    public int getMaxAndSum(int[] nums, int numSlots) {
        int n = nums.length;
        int total = 0;
        
        for (int bit = 14; bit >= 0; bit--) {
            int count = 0;
            for (int num : nums) {
                if (((num >> bit) & 1) == 1) {
                    count++;
                }
            }
            
            if (count <= numSlots) {
                total += (1 << bit) * count;
                numSlots -= count;
            } else {
                total += (1 << bit) * numSlots;
                break;
            }
        }
        
        return total;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2172 (Maximum AND Sum of Array)?

This page provides optimized solutions for LeetCode problem 2172 (Maximum AND Sum of Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2172 (Maximum AND Sum of Array)?

The time complexity for LeetCode 2172 (Maximum AND Sum of Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2172 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2172 in Java, C++, or Python.

Back to LeetCode Solutions