1 Twice Greedy
Considering these situations
1.1 K <= A.size()
- + + + + + K + +++++K+ +++++ K + , the first element is
K % 2
addedaccording topositive and negative, the others can be added up - − − − − − K − -----K- −−−−− K − ,take the negativesum of
[0, K - 1]
all, and accumulate the others - − − K − + + + --K-+++ −−K−+++ , When
K < =负数个数
the second step is done - − − − − + K + + ----+K++ −−−−+K++ , When
K > 负数个数
, the negative number is summed up, and the positive number is done according to the first step
1.2 K > A.size()
- + + + + + + + +++++++ +++++++ , Same as the first in the previous step
- − − − − − − − ------- −−−−−−− , The first element is
K % 2
added upaccording to theplus and minus, the others are取负
added up - − − K − + + + --K-+++ −−K−+++ , Thenegative part is taken positive andaccumulated and
追踪最小绝对值
compared when the first positive number is reached, ①If the former is small and the remaining K will be placed, then subtract 2 times the minimum value and add the current positive number, and then accumulate; ② If the latter is small, and the remaining K will place an order, the positive number isK % 2
added upaccording to theplus and minus, and the others are added up - − − − − + K + + ----+K++ −−−−+K++ , Same as the fourth step in the previous step
But in fact, sorting by absolute value from largest to smallest, you can achieve the above situation with only a small amount of judgment. The specific code is as follows
class Solution {
private:
static bool cmp(int a, int b) {
return abs(a) > abs(b);
}
public:
int largestSumAfterKNegations(vector<int>& A, int K) {
// 1.按绝对值从大到小排列
sort(A.begin(), A.end(), cmp);
int sum = 0;
for (auto& num : A) {
// 2.负值变正
if (num < 0 && K > 0) {
num *= -1;
K--;
}
sum += num;
}
// 3.处理K > A.size()情况
if (K > 0 && K % 2 == 1) sum -= 2 * A[A.size() - 1];
return sum;
}
};