Golang Leetcode 1005. Maximize Sum Of Array After K Negations.go

时间:2022-06-20
本文章向大家介绍Golang Leetcode 1005. Maximize Sum Of Array After K Negations.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

思路

先循环k次,每次把最小值前加负号,然后遍历求和

code

func largestSumAfterKNegations(A []int, K int) int {
	sum := 0
	for K > 0 {
		small := 0
		for i := 0; i < len(A); i++ {
			if A[i] < A[small] {
				small = i
			}
		}
		A[small] = A[small] * -1
		K--
	}
	for _, v := range A {
		sum += v
	}
	return sum
}

更多内容请移步我的repo:https://github.com/anakin/golang-leetcode