Skip to content

Commit 0fa7eee

Browse files
authored
Create 1005-maximize-sum-of-array-after-k-negations.js
1 parent 64863b7 commit 0fa7eee

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} A
3+
* @param {number} K
4+
* @return {number}
5+
*/
6+
const largestSumAfterKNegations = function(A, K) {
7+
if (A.length === 0) return 0;
8+
A.sort((a, b) => a - b);
9+
let res = 0;
10+
let posIdx;
11+
for (let i = 0, num = 0; i < A.length; i++) {
12+
if (num < K) {
13+
if (A[i] < 0) {
14+
A[i] = -A[i];
15+
} else {
16+
if (posIdx == null) {
17+
posIdx = Math.abs(A[i]) - Math.abs(A[i - 1]) > 0 ? i - 1 : i;
18+
}
19+
A[posIdx] = -A[posIdx];
20+
}
21+
num++;
22+
}
23+
}
24+
res = A.reduce((ac, el) => ac + el, 0);
25+
return res;
26+
};

0 commit comments

Comments
 (0)