Skip to content

Commit 282a646

Browse files
committed
1005 codes updated.
1 parent 59b9222 commit 282a646

File tree

1 file changed

+30
-9
lines changed
  • 1005-Maximize-Sum-Of-Array-After-K-Negations/cpp-1005

1 file changed

+30
-9
lines changed
Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,48 @@
1+
/// Source : https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/
2+
/// Author : liuyubobobo
3+
/// Time : 2019-03-09
4+
15
#include <iostream>
26
#include <vector>
7+
#include <numeric>
38

49
using namespace std;
510

611

12+
/// Sorting and Greedy
13+
/// Time Complexity: O(nlogn)
14+
/// Space Complexity: O(1)
715
class Solution {
816
public:
9-
int findJudge(int N, vector<vector<int>>& trust) {
17+
int largestSumAfterKNegations(vector<int>& A, int K) {
18+
19+
sort(A.begin(), A.end());
20+
21+
int neg = 0;
22+
bool hasZero = false;
23+
for(int i = 0; i < A.size(); i ++)
24+
if(A[i] < 0) neg ++;
25+
else if(A[i] == 0) hasZero = true;
1026

11-
vector<int> indegrees(N, 0), outdegrees(N, 0);
12-
for(const vector<int>& e: trust)
13-
outdegrees[e[0] - 1] ++,
14-
indegrees[e[1] - 1] ++;
27+
int t = min(neg, K);
28+
for(int i = 0; i < t; i ++)
29+
A[i] = -A[i];
30+
K -= t;
1531

16-
for(int i = 0; i < N; i ++)
17-
if(indegrees[i] == N - 1 && outdegrees[i] == 0)
18-
return i + 1;
19-
return -1;
32+
if(K && !hasZero && K % 2){
33+
sort(A.begin(), A.end());
34+
A[0] = -A[0];
35+
}
36+
37+
return accumulate(A.begin(), A.end(), 0);
2038
}
2139
};
2240

2341

2442
int main() {
2543

44+
vector<int> A1 = {4, 2, 3};
45+
cout << Solution().largestSumAfterKNegations(A1, 1) << endl;
46+
2647
return 0;
2748
}

0 commit comments

Comments
 (0)