Skip to content

Instantly share code, notes, and snippets.

@AKASH-ALAM
Created November 16, 2022 16:35
Show Gist options
  • Save AKASH-ALAM/a179de1b52dd73417ea75d026719f51a to your computer and use it in GitHub Desktop.
Save AKASH-ALAM/a179de1b52dd73417ea75d026719f51a to your computer and use it in GitHub Desktop.
I. Array Negations
/**
* Author : Pnictogen
* Task :
* Algo :
**/
#include <bits/stdc++.h>
#define endl '\n'
#define sqr(x) (x) * (x)
#define gcd(x,y) __gcd(x,y)
#define lcm(x,y) ((x/gcd(x,y)) * y)
#define sz(x) (int)x.size()
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define prec(x) fixed<<setprecision(x)
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define min4(a,b,c,d) min(a,min(b,min(c,d)))
#define max4(a,b,c,d) max(a,max(b,max(c,d)))
#define unsyncIO ios_base::sync_with_stdio(false); cin.tie(nullptr)
using namespace std;
using ll = long long;
using db = double;
using ld = long double;
using ull = unsigned long long;
const ld PI = acos((ld) - 1);
const int MOD = 1e9 + 7;
const ll INF = 2e18 + 1;
const ld EPS = 1e-9;
const int MX = 2e5;
#ifdef LOCAL
#include"debug.h"
#else
#define debug(...)
#endif
// Note : Each element in the array can be negated multiple times.
void solve() {
int n, k, pos = 0; cin >> n >> k;
vector <int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
sort(v.begin(), v.end());
ll sum = 0;
for (int i = 0; i < k; i++) {
if (v[i] <= 0) {
v[i] = -v[i];
pos++; // count how many negatiove we made positive
} else break;
}
k = (k - pos) % 2; // if we negation twice of a element it remains same.
if (k == 1) {// if k is 1 then we make the smallest negation so that the sum is max
sort(v.begin(), v.end());
v[0] = -v[0];
}
sum = accumulate(v.begin(), v.end(), 0ll);
/*for (int data : v) cout << data << " ";
cout << endl;*/
cout << sum << endl;
}
int main() {
#ifdef LOCAL
clock_t tStart = clock();
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
unsyncIO;
int t = 1; cin >> t;
while (t--) {
solve();
}
#ifdef LOCAL
cerr << "\nRuntime: " << (ld) (clock() - tStart) / CLOCKS_PER_SEC << " Seconds" << endl;
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment