leetcode

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit 9674c7aad3941e9a17f752674e2db1ee6a32b240
parent e4a43d6ce64312d5165af31765e0ea701a6c4445
Author: Andrew Laack <andrew@laack.co>
Date:   Fri,  4 Jul 2025 11:55:04 -0500

Completed last stone weight

Diffstat:
Alast-stone-weight/last-stone-weightV1.py | 31+++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+), 0 deletions(-)

diff --git a/last-stone-weight/last-stone-weightV1.py b/last-stone-weight/last-stone-weightV1.py @@ -0,0 +1,31 @@ +from heapq import heappop, heappush, heapify + +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + + # heapq is a min-heap. + + stones = [-x for x in stones] + heapify(stones) + heap = stones + + while len(heap) > 1: + + # y + heaviest = heappop(heap) + + # x + second_heaviest = heappop(heap) + + # if x == y both destroyed + if heaviest == second_heaviest: + continue + + # x != y + heaviest = heaviest - second_heaviest + heappush(heap, heaviest) + + if len(heap) == 1: + return heap[0] * -1 + + return 0