leetcode 3727. 最大交替平方和 中等

给你一个整数数组 nums。你可以以任意顺序 重新排列元素。

数组 arr 的 交替得分定义为:

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

在对 nums 重新排列后,返回其 最大可能的交替得分。

示例 1:

输入: nums = 1,2,3

输出: 12

解释:

nums 的一种可行重排为 [2,1,3],该排列在所有可能重排中给出了最大交替得分。

交替得分计算如下:

score = 2^2 - 1^2 + 3^2 = 4 - 1 + 9 = 12

示例 2:

输入: nums = 1,-1,2,-2,3,-3

输出: 16

解释:

nums 的一种可行重排为 [-3,-1,-2,1,3,2],该排列在所有可能重排中给出了最大交替得分。

交替得分计算如下:

score = (-3)^2 - (-1)^2 + (-2)^2 - (1)^2 + (3)^2 - (2)^2 = 9 - 1 + 4 - 1 + 9 - 4 = 16

提示:

  • 1 <= nums.length <= 10^5
  • -4 * 10^4 <= nums[i] <= 4 * 10^4

分析:用贪心的思路。由于每次求得分都是 numsi 的平方项,因此可以不用考虑 numsi 的正负性,只需要将绝对值尽可能大的数放在奇数位置,绝对值小的数放在偶数位置即可。

首先将 nums 中的所有数转成绝对值后从小排序,再用两个指针,分别指向排序后数组的首尾。每次加上末尾的数的平方,再减去首部的数的平方,直到所有数都被加减过为止。

cpp 复制代码
class Solution {
public:
    int change(int a)
    {
        return a>=0?a:-a;
    }
    long long maxAlternatingSum(vector<int>& nums) {
        int n=nums.size();
        vector<int>pos;
        for(int i=0;i<n;++i)
            pos.push_back(change(nums[i]));
        sort(pos.begin(),pos.end());
        long long ans=0;
        for(int i=n,j=-1,t=0;i-1>j;t++)
        {
            if(t%2==0)i-=1,ans+=1LL*pos[i]*pos[i];
            else j+=1,ans-=1LL*pos[j]*pos[j];
        }
        return ans;
    }
};
相关推荐
Xin7702 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao8 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1239 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi9 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 天前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2081 天前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 天前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode