- 这真是开了眼了,还有种完全无厘头的题目
- 竟然能有这么高明的解法
- 真是四两拨千斤的神奇之感
- 解法中使用了Lambda函数,C++的高级特性,不太会用,写出来太酷了
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
int largestSumAfterKNegations(std::vector<int>& nums, int k) {
std::sort(nums.begin(), nums.end(), [](int a, int b) { return std::abs(a) > std::abs(b); });
int kt = k;
for (int i = 0; i < nums.size(); ++i) {
if (nums.at(i) < 0 && kt > 0) {
nums.at(i) *= -1;
--kt;
}
}
if (kt & 1)
nums.at(nums.size() - 1) *= -1;
int sum = 0;
for (int i: nums)
sum += i;
return sum;
}
};
int main()
{
std::vector<int> nums {-3, -6, 2, 3, -7};
Solution s;
std::cout << s.largestSumAfterKNegations(nums, 0) << std::endl;
return 0;
}
- 求vector元素和有更棒的写法,但奈何一点都不理解,就不用了
- 汇总