Leetcode Problem 2897. Apply Operations on Array to Maximize Sum of Squares

2897. Apply Operations on Array to Maximize Sum of Squares

Leetcode Solutions

Count Bits and Construct Maximum Numbers

  1. Initialize an array count of length 32 (to represent 32 bits) to store the frequency of set bits at each bit position across all numbers in the input array.\n2. Iterate over each number in the input array and for each bit position, increment the corresponding count index if the bit is set.\n3. Initialize a variable res to store the result and a variable mod with the value 10^9 + 7 for taking the modulo of the final result.\n4. Repeat the following steps k times to construct the k largest numbers:\n a. Initialize a variable cur to store the current number being constructed.\n b. Iterate over the count array from the most significant bit to the least significant bit:\n i. If the count at the current bit position is greater than 0, decrement the count and set the corresponding bit in cur.\n c. Add the square of cur to res, taking the modulo with mod.\n5. Return the value of res.
UML Thumbnail

Greedy Prefix and Suffix Bit Counting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...