LeetCode solutions

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

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 124ms, memory 30.6MB, accepted 2025-12-30.

python
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

Source