Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
maximize-sum-of-array-after-k-negations.cpp 943 Bytes
Copy Edit Raw Blame History
kamyu authored 2019-03-10 17:23 +08:00 . Update maximize-sum-of-array-after-k-negations.cpp
// Time: O(n) ~ O(n^2), O(n) on average.
// Space: O(1)
// quick select solution
class Solution {
public:
int largestSumAfterKNegations(vector<int>& A, int K) {
nth_element(A.begin(), A.begin() + K, A.end());
int remain = K;
for (int i = 0; i < K; ++i) {
if (A[i] < 0) {
A[i] = -A[i];
--remain;
}
}
return accumulate(A.cbegin(), A.cend(), 0) -
(remain % 2) * *min_element(A.cbegin(), A.cend()) * 2;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
int largestSumAfterKNegations(vector<int>& A, int K) {
sort(A.begin(), A.end());
int remain = K;
for (int i = 0; i < K && A[i] < 0; ++i) {
A[i] = -A[i];
--remain;
}
return accumulate(A.cbegin(), A.cend(), 0) -
(remain % 2) * *min_element(A.cbegin(), A.cend()) * 2;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search