java.lang.Object
g2101_2200.s2172_maximum_and_sum_of_array.Solution

public class Solution extends Object
2172 - Maximum AND Sum of Array.<p>Hard</p> <p>You are given an integer array <code>nums</code> of length <code>n</code> and an integer <code>numSlots</code> such that <code>2 * numSlots >= n</code>. There are <code>numSlots</code> slots numbered from <code>1</code> to <code>numSlots</code>.</p> <p>You have to place all <code>n</code> integers into the slots such that each slot contains at <strong>most</strong> two numbers. The <strong>AND sum</strong> of a given placement is the sum of the <strong>bitwise</strong> <code>AND</code> of every number with its respective slot number.</p> <ul> <li>For example, the <strong>AND sum</strong> of placing the numbers <code>[1, 3]</code> into slot <code>1</code> and <code>[4, 6]</code> into slot <code>2</code> is equal to <code>(1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4</code>.</li> </ul> <p>Return <em>the maximum possible <strong>AND sum</strong> of</em> <code>nums</code> <em>given</em> <code>numSlots</code> <em>slots.</em></p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums = [1,2,3,4,5,6], numSlots = 3</p> <p><strong>Output:</strong> 9</p> <p><strong>Explanation:</strong> One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3.</p> <p>This gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums = [1,3,10,4,7,1], numSlots = 9</p> <p><strong>Output:</strong> 24</p> <p><strong>Explanation:</strong> One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9.</p> <p>This gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.</p> <p>Note that slots 2, 5, 6, and 8 are empty which is permitted.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 <= numSlots <= 9</code></li> <li><code>1 <= n <= 2 * numSlots</code></li> <li><code>1 <= nums[i] <= 15</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • maximumANDSum

      public int maximumANDSum(int[] nums, int numSlots)