Approach
Sorting and greedy selection
For Maximum Alternating Sum of Squares, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 31 lines of C++ from the credited upstream file maximum-alternating-sum-of-squares.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long maxAlternatingSum(vector<int>& nums) {8 vector<int> arr(size(nums));9 for (int i = 0; i < size(arr); ++i) {10 arr[i] = nums[i] * nums[i];11 }12 nth_element(begin(arr), begin(arr) + (size(nums) / 2), end(arr));13 return accumulate(cbegin(arr), cend(arr), 0ll) - 2 * accumulate(cbegin(arr), cbegin(arr) + (size(arr) / 2), 0ll);14 }15};16 17181920class Solution2 {21public:22 long long maxAlternatingSum(vector<int>& nums) {23 vector<int> arr(size(nums));24 for (int i = 0; i < size(arr); ++i) {25 arr[i] = nums[i] * nums[i];26 }27 sort(begin(arr), end(arr));28 return accumulate(cbegin(arr), cend(arr), 0ll) - 2 * accumulate(cbegin(arr), cbegin(arr) + (size(arr) / 2), 0ll);29 }30};31