Merge pull request #304 from fusunx/master

1005.K次取反.md Javascript
This commit is contained in:
Carl Sun 2021-06-01 10:44:38 +08:00 committed by GitHub
commit 7b3f8ea4dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 22 additions and 0 deletions

View File

@ -140,7 +140,29 @@ class Solution:
Go
Javascript:
```Javascript
var largestSumAfterKNegations = function(nums, k) {
nums.sort((a, b) => {
return Math.abs(b) - Math.abs(a)
})
for(let i = 0; i < nums.length; i++) {
if(nums[i] < 0 && k > 0) {
nums[i] *= -1
k--
}
}
if(k > 0 && k % 2 === 1) {
nums[nums.length - 1] *= -1
}
k = 0
return nums.reduce((a, b) => {
return a + b
})
};
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)