Leetcode Note: Go - Maximize Sum of Array After K Negations
Maximize Sum Of Array After K Negations - LeetCode
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/
- Go 言語で取り組んだメモ
回答
Go Solution with sort - LeetCode Discuss
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/854867/Go-Solution-with-sort
func largestSumAfterKNegations(A []int, K int) int {
sort.Ints(A)
var pos int
for K > 0 {
if A[pos] == 0 {
break
}
if pos < len(A)-1 {
if (A[pos] < 0 && A[pos+1] < 0) || A[pos]*-1 > A[pos+1] {
A[pos] *= -1
pos++
} else {
A[pos] *= -1
}
} else {
A[pos] *= -1
}
K--
}
var total int
for _, n := range A {
total += n
}
return total
}