mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
1005.K次取反.md Javascript
This commit is contained in:
@ -140,7 +140,29 @@ class Solution:
|
|||||||
Go:
|
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)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
Reference in New Issue
Block a user