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
自己写的,记录一下
原文地址:https://www.cnblogs.com/houtianzym/p/10556113.html
时间: 2024-10-31 15:35:22