#2897

Apply Operations on Array to Maximize Sum of Squares

Hard
ArrayHash TableGreedyBit ManipulationGreedy AlgorithmsSortingArray Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(1)

Instead of brute-forcing through all pairs, we can recognize that the AND and OR operations can be used to maximize individual elements. The goal is to maximize the largest k elements in the array, which can be achieved by applying the operations strategically.

⚙️

Algorithm

3 steps
  1. 1Step 1: Identify the maximum element in the array, as it will contribute the most to the sum of squares.
  2. 2Step 2: Use the AND and OR operations to combine elements to maximize the largest values.
  3. 3Step 3: After maximizing, sort the array and select the k largest elements to compute their sum of squares.
solution.py3 lines
1def maxSumOfSquares(nums, k):
2    nums.sort(reverse=True)
3    return sum(x*x for x in nums[:k]) % (10**9 + 7)

Complexity note: The time complexity is O(n log n) due to the sorting step, which is much more efficient than the O(n²) of the brute force approach.

  • 1The AND and OR operations can be used to manipulate the bits of numbers to maximize their values.
  • 2Greedily maximizing the largest elements in the array will yield the highest sum of squares.

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