Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two versions: Max-heap, Min-heap, 4 lines each solution in Clear category for The Final Stone by Phil15
import heapq as H
# Sadly, we can not import "_heapify_max", "_heappop_max" and "_heapreplace_max" from "heapq" on CheckiO
# (you can on your computer, those private functions of the "heapq" modules are only used for the implemenation of the function "merge")
# but with those, I can manage the list of weights as a max-heap like I really want.
# I tested it on my computer since I can not on CheckiO. You will have to believe me or test it yourself.
def final_stone(h: list[int]) -> int:
H._heapify_max(h)
while len(h) >= 2: H._heapreplace_max(h, w) if (w := H._heappop_max(h) - h[0]) else H._heappop_max(h)
return h[0] if h else 0
# Or with a min-heap with negative weights, as it is intended by the "heapq" module.
def final_stone(stones: list[int]) -> int:
H.heapify(h := [-w for w in stones])
while len(h) >= 2: H.heapreplace(h, w) if (w := H.heappop(h) - h[0]) else H.heappop(h)
return -h[0] if h else 0
July 24, 2022
Comments: