码迷,mamicode.com
首页 > 其他好文 > 详细

Maximize Sum Of Array After K Negations

时间:2019-03-19 01:30:22      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:span   pytho   turn   return   max   min   lse   算法   python   

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

标签:span   pytho   turn   return   max   min   lse   算法   python   

原文地址:https://www.cnblogs.com/houtianzym/p/10556113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!