mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
479 B
479 B
class Solution {
static bool cmp(int a, int b) {
return abs(a) < abs(b);
}
public:
int largestSumAfterKNegations(vector<int>& A, int K) {
sort(A.begin(), A.end(), cmp);
for (int i = A.size() - 1; i >= 0; i--) {
if (A[i] < 0 && K > 0) {
A[i] *= -1;
K--;
}
}
while (K--) A[0] *= -1;
int result = 0;
for (int a : A) result += a;
return result;
}
};