4078. Maximum Alternating Sum of Squares
My accepted Python solution to LeetCode problem 4078, Maximum Alternating Sum of Squares, running in 124ms.
- Difficulty: Medium
- Python
- Runtime 124ms
- Memory 30.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 124ms, memory 30.6MB, accepted 2025-12-30.
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
squares = sorted([x*x for x in nums], reverse=True)
# Number of even positions (positive contribution)
even_count = (n + 1) // 2
# Number of odd positions (negative contribution)
odd_count = n // 2
# Put largest squares at even positions, smallest at odd
result = sum(squares[:even_count]) - sum(squares[even_count:])
return result