[LeetCode] Maximum Alternating Sum of Squares

3727. Maximum Alternating Sum of Squares

You are given an integer array nums. You may rearrange the elements in any order.

The alternating score of an array arr is defined as:

  • score = arr[0]2 - arr[1]2 + arr[2]2 - arr[3]2 + ...

Return an integer denoting the maximum possible alternating score of nums after rearranging its elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long maxAlternatingSum(vector<int>& nums) {
for(auto& n : nums) n = abs(n);
deque<int> A(begin(nums), end(nums));
sort(begin(A), end(A));
long long res = 0, op = 0;
while(A.size()) {
if(op) {
res -= 1ll * A.front() * A.front(); A.pop_front();
} else {
res += 1ll * A.back() * A.back(); A.pop_back();
}
op = !op;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/28/PS/LeetCode/maximum-alternating-sum-of-squares/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.