Maximize Sum Of Array After K Negations

Posted houtianzym

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maximize Sum Of Array After K Negations相关的知识,希望对你有一定的参考价值。

1         heapq.heapify(A)
2         for i in range(K):
3             heapq.heapreplace(A, -A[0])
4             
5         return sum(A)

最近在看python,该题现在最快的算法

 1 A.sort()
 2         bZero = False
 3         ret = 0;
 4         minNum = sys.maxsize
 5         for a in A:
 6             if a < 0:
 7                 if K > 0:
 8                     a = -a
 9                     K -= 1
10                 ret += a
11             elif a == 0:
12                 bZero = True
13             else:
14                 ret+=a
15                 
16             minNum = min(minNum, a)
17         
18         if bZero:
19             return ret
20         else:
21             if K%2 == 1:
22                 ret -= minNum*2
23                 
24         return ret

自己写的,记录一下

以上是关于Maximize Sum Of Array After K Negations的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1005. Maximize Sum Of Array After K Negations 解题报告

LeetCode --- 1005. Maximize Sum Of Array After K Negations 解题报告

leetcode 1005 Maximize Sum Of Array After K Negations & leetcode 1006 Clumsy Factorial

LeetCode 1005. Maximize Sum Of Array After K Negations (K 次取反后最大化的数组和)

Minimum Sum of Array(map迭代器)

LeetCode --- 1480. Running Sum of 1d Array 解题报告