I - Array Negations

You are given an array a of n integers, and an integer k. You have to make k negation operations such that at each operation you need to choose an element ai from the array and replace it with −ai.

Your task is to find the optimal way to make the k negation operations such that at the end the sum of the array a is as maximal as possible. Can you?

Input
The first line contains an integer T (1≤T≤100) specifying the number of test cases.

The first line of each test case contains two integers n and k (1≤n≤104, 0≤k≤104), in which n is the size of the array, and k is the number of negation operations to be made.

Then a line follows contains n integers a1,⋯,an (−100≤ai≤100), giving the array a.

Output
For each test case, print a single line containing the maximum sum of array a after making the required number of negation operations.

Example
Input
3
3 1
4 6 2
4 2
-1 0 2 1
5 2
1 7 -4 2 -3
Output
8
4
17
Note
In the first test case, the optimal way is to make the negation operation on a3. After this, the array will be = [4,6,−2], and its sum is 8.
思路
统计数组中负数的个数,为num,如果k>num,则说明所有的负数都会被改成正数,剩下的k-num次都只取反最小的正数就好了;否则的话,那就先把数组排序一下,只把前k个取反就好啦~

#include<bits/stdc++.h>
using namespace std;
int a[10001];
int main()
{
    std::ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        int n,k;
        cin>>n>>k;
        int num=0;//负数的个数
        for(int i=0; i<n; i++)
        {
            cin>>a[i];
            if(a[i]<0)
            {
                num++;
            }
        }
        if(num<=k)
        {
            int minn=99999999;
            int x=-1;
            for(int i=0; i<n; i++)
            {
                if(a[i]<0)
                {
                    a[i]=-a[i];
                }
                if(a[i]<minn)
                {
                    minn=a[i];
                    x=i;
                }
            }
            if((k-num)%2!=0)
            {
                a[x]=-a[x];
            }
        }
        else
        {
            sort(a,a+n);
            for(int i=0; i<k; i++)
                a[i]=-a[i];
        }
        long long int sum=0;
        for(int i=0; i<n; i++)
            sum+=a[i];
        cout<<sum<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值