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

 

 

地址:https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations/

 

 1 '''
 2 
 3 示例 1:
 4 
 5 输入:A = [4,2,3], K = 1
 6 输出:5
 7 解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。
 8 示例 2:
 9 
10 输入:A = [3,-1,0,2], K = 3
11 输出:6
12 解释:选择索引 (1, 2, 2) ,然后 A 变为 [3,1,0,2]。
13 示例 3:
14 
15 输入:A = [2,-3,-1,5,-4], K = 2
16 输出:13
17 解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
18 
19 20 21 22 '''
23 
24 
25 class Solution:
26     def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
27         newSort = sorted(nums)
28         for i in range(k):
29             newSort[0] = -newSort[0]
30             newSort = sorted(newSort)
31         return sum(newSort)

 

 

来源:力扣(LeetCode)
链接:
https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations
posted @ 2021-07-11 22:54  菜小鱼~  阅读(98)  评论(0编辑  收藏  举报