3727. Maximum Alternating Sum of Squares Medium
1/**
2 * [3727] Maximum Alternating Sum of Squares
3 *
4 * You are given an integer array nums. You may rearrange the elements in any order.
5 * The alternating score of an array arr is defined as:
6 *
7 * score = arr[0]^2 - arr[1]^2 + arr[2]^2 - arr[3]^2 + ...
8 *
9 * Return an integer denoting the maximum possible alternating score of nums after rearranging its elements.
10 *
11 * <strong class="example">Example 1:
12 * <div class="example-block">
13 * Input: <span class="example-io">nums = [1,2,3]</span>
14 * Output: <span class="example-io">12</span>
15 * Explanation:
16 * A possible rearrangement for nums is [2,1,3], which gives the maximum alternating score among all possible rearrangements.
17 * The alternating score is calculated as:
18 * score = 2^2 - 1^2 + 3^2 = 4 - 1 + 9 = 12
19 * </div>
20 * <strong class="example">Example 2:
21 * <div class="example-block">
22 * Input: <span class="example-io">nums = [1,-1,2,-2,3,-3]</span>
23 * Output: <span class="example-io">16</span>
24 * Explanation:
25 * A possible rearrangement for nums is [-3,-1,-2,1,3,2], which gives the maximum alternating score among all possible rearrangements.
26 * The alternating score is calculated as:
27 * score = (-3)^2 - (-1)^2 + (-2)^2 - (1)^2 + (3)^2 - (2)^2 = 9 - 1 + 4 - 1 + 9 - 4 = 16
28 * </div>
29 *
30 * Constraints:
31 *
32 * 1 <= nums.length <= 10^5
33 * -4 * 10^4 <= nums[i] <= 4 * 10^4
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/maximum-alternating-sum-of-squares/
39// discuss: https://leetcode.com/problems/maximum-alternating-sum-of-squares/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44 pub fn max_alternating_sum(nums: Vec<i32>) -> i64 {
45
46 }
47}
48
49// submission codes end
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn test_3727() {
57 }
58}
59Back
© 2026 bowen.ge All Rights Reserved.