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;
    }
};
相关推荐
Navigator_Z2 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
wy_hhxx3 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK3 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
Navigator_Z3 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
Navigator_Z3 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
驭渊的小故事4 天前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
郝学胜-神的一滴5 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger5 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z5 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
Pniubi6 天前
力扣2 . 两数相加
算法·leetcode·职场和发展