Update 1005.K次取反后最大化的数组和.md

添加 1005.K次取反后最大化的数组和.md Golang版本
This commit is contained in:
yangxk201396
2021-06-16 02:06:23 +08:00
committed by GitHub
parent 3461b91704
commit 7221797cca

View File

@ -138,6 +138,30 @@ class Solution:
```
Go
```Go
func largestSumAfterKNegations(nums []int, K int) int {
sort.Slice(nums, func(i, j int) bool {
return math.Abs(float64(nums[i])) > math.Abs(float64(nums[j]))
})
for i := 0; i < len(nums); i++ {
if K > 0 && nums[i] < 0 {
nums[i] = -nums[i]
K--
}
}
if K%2 == 1 {
nums[len(nums)-1] = -nums[len(nums)-1]
}
result := 0
for i := 0; i < len(nums); i++ {
result += nums[i]
}
return result
}
```
Javascript: