小C的帖子吸引力最大化-题解.cpp

63 阅读1分钟

小C的帖子吸引力最大化

问题描述

小C管理了一个帖子社区,他发布了nn个帖子,每个帖子都有其点赞数和点踩数。小C希望能够组合任意数量的帖子,以便让这些帖子的组合在整个社区中产生最大的吸引力。

帖子的吸引力定义为其点赞数和点踩数差的绝对值,即 |x - y|,其中xx是点赞数,yy是点踩数。小C想要找出一组帖子,使得它们的总点赞数和总点踩数的差的绝对值最大化。

你的任务是帮助小C计算出可以达到的最大吸引力。


测试样例

样例1:

输入:n = 4,a = [4, 2, 1, 1],b = [2, 1, 4, 4]
输出:6

样例2:

输入:n = 3,a = [10, 20, 30],b = [15, 25, 5]
输出:25

样例3:

输入:n = 5,a = [1, 5, 3, 7, 9],b = [2, 6, 4, 8, 10]
输出:5

思路

最大化差的绝对值,那么我们只需要取x-y,y-x为正数的值求和取max即可

code


#include <iostream>
#include <vector>

using namespace std;

int solution(int n, vector<int>& a, vector<int>& b) {
    int ans1=0,ans2=0;
    for (int i = 0; i < n; ++i) {
        if (a[i]>b[i]){
            ans1+=a[i]-b[i];
        }
        else{
            ans2+=b[i]-a[i];
        }
    }
    return max(ans1,ans2);
}

int main() {
    vector<int> v1 = {4, 2, 1, 1};
    vector<int> v2 = {2, 1, 4, 4};
    vector<int> v3 = {10, 20, 30};
    vector<int> v4 = {15, 25, 5};
    vector<int> v5 = {1, 5, 3, 7, 9};
    vector<int> v6 = {2, 6, 4, 8, 10};

    cout << (solution(4, v1, v2) == 6) << endl;
    cout << (solution(3, v3, v4) == 25) << endl;
    cout << (solution(5, v5, v6) == 5) << endl;
    return 0;
}