示例 1:
输入:A = [4,2,3], K = 1
输出:5
解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。
示例 2:
输入:A = [3,-1,0,2], K = 3
输出:6
解释:选择索引 (1, 2, 2) ,然后 A 变为 [3,1,0,2]。
示例 3:
输入:A = [2,-3,-1,5,-4], K = 2
输出:13
解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
提示:
1 <= A.length <= 10000
1 <= K <= 10000
-100 <= A[i] <= 100
每次找最小的取反:
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
for _ in range(K):
min_index = A.index(min(A))
A[min_index] = -A[min_index]
return sum(A)
先排序,对负的取反,正的最小一直取反:
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort()
for i in range(K):
if A[i] < 0:
A[i] = -A[i]
else:
return sum(A) if (K-i) % 2 == 0 else sum(A) - min(A[i-1], A[i])*2
return sum(A)