-
Notifications
You must be signed in to change notification settings - Fork 1
/
Maximize sum after K negations.cpp
60 lines (54 loc) · 1.07 KB
/
Maximize sum after K negations.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
long long int sumArray(long long int* a, int n)
{
long long int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return sum;
}
long long int maximizeSum(long long int a[], int n, int k)
{
// Your code goes here
sort(a, a + n);
int i = 0;
for (i = 0; i < n; i++) {
if (k && a[i] < 0) {
a[i] *= -1;
k--;
continue;
}
break;
}
if (i == n)
i--;
if (k == 0 || k % 2 == 0)
return sumArray(a, n);
if (i != 0 && abs(a[i]) >= abs(a[i - 1]))
i--;
a[i] *= -1;
return sumArray(a, n);
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n, k;
cin>>n>>k;
long long int a[n+5];
for(int i=0;i<n;i++)
cin>>a[i];
Solution ob;
cout<<ob.maximizeSum(a, n, k)<<endl;
}
return 0;
}
// } Driver Code Ends