-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode1005-maximize-sum-of-array-after-k-negations_classification.cpp
73 lines (70 loc) · 2.04 KB
/
leetcode1005-maximize-sum-of-array-after-k-negations_classification.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
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<vector>
#include<algorithm>
#include<iostream>
#include<numeric>
using namespace std;
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
int m = 0; // 负数的个数
for (auto& num : nums)
if (num < 0) m++;
auto sum = accumulate(nums.begin(), nums.end(), 0);
if (m == 0 && k % 2 == 0)
return sum;
else if (m == 0 && k % 2 == 1)
{
auto it = min_element(nums.begin(), nums.end());
return sum - 2*(*it);
}
else if (m > 0 && m >= k)
{
sort(nums.begin(), nums.end());
int sum1 = 0;
for (int i = 0; i < nums.size(); i++)
{
if (i <= k-1) /* 题意: k >= 1, k-1不会成负数 */
sum1 += -nums[i];
else sum1 += nums[i];
}
return sum1;
}
else if (m > 0 && m < k)
{
if ((k - m) % 2 == 0)
{
int sum1 = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] < 0)
sum1 += -nums[i];
else sum1 += nums[i];
}
return sum1;
}
else {
int sum1 = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] < 0)
nums[i] = -nums[i];
sum1 += nums[i];
}
sort(nums.begin(), nums.end());
auto it = min_element(nums.begin(), nums.end());
return sum1 - 2*(*it);
}
}
return 0;
}
};
// Test
int main()
{
Solution sol;
vector<int> nums = {5, 6, 9, -3, 3};
int k = 2;
auto res = sol.largestSumAfterKNegations(nums, k);
cout << res << endl;
return 0;
}