參考:https://blog.csdn.net/baidu_27643275/article/details/88878612
heapq模塊可以接受元組對象,默認元組的第一個元素作為priority,即按照元組的第一個元素構成 小根堆,若第一個元素是原先的負數,則可以利用元組構造大頂堆,符合一般的升序需求
heappush( Q , tuple )
利用元組構建 大頂堆
from heapq import *
def FindMaxProfit(profits, key=lambda x: -x):
maxHeap1 = []
for i in range(len(profits)):
heappush(maxHeap1, (-profits[i], profits[i])) # 大頂堆
# heappush(maxHeap1, profits[i]) # 默認小頂堆
return heappop(maxHeap1)
# for test
profits = [3, 2, 4, 9]
print(FindMaxProfit(profits)) # (-9, 9) 最大值是元組的第二個元素 9