#3727
Maximum Alternating Sum of Squares
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
To maximize the alternating score, place the largest squares at even indices and the smallest squares at odd indices. This ensures the highest positive contributions and lowest negative contributions.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array in descending order.
- 2Step 2: Calculate the score using the sorted array by adding squares at even indices and subtracting squares at odd indices.
- 3Step 3: Return the calculated score.
solution.py4 lines
1def maxAlternatingSum(nums):
2 nums.sort(reverse=True)
3 score = sum(nums[i] ** 2 if i % 2 == 0 else -nums[i] ** 2 for i in range(len(nums)))
4 return scoreℹ
Complexity note: Sorting the array takes O(n log n), and calculating the score takes O(n), leading to O(n log n) overall.
- 1Even indices should have larger squares.
- 2Sorting helps maximize positive contributions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.