1
+ // / Source : https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/
2
+ // / Author : liuyubobobo
3
+ // / Time : 2019-03-09
4
+
1
5
#include < iostream>
2
6
#include < vector>
7
+ #include < numeric>
3
8
4
9
using namespace std ;
5
10
6
11
12
+ // / Sorting and Greedy
13
+ // / Time Complexity: O(nlogn)
14
+ // / Space Complexity: O(1)
7
15
class Solution {
8
16
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 ;
10
26
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 ;
15
31
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 );
20
38
}
21
39
};
22
40
23
41
24
42
int main () {
25
43
44
+ vector<int > A1 = {4 , 2 , 3 };
45
+ cout << Solution ().largestSumAfterKNegations (A1, 1 ) << endl;
46
+
26
47
return 0 ;
27
48
}
0 commit comments