Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1046. Last Stone Weight #175

Open
jrmullen opened this issue Jul 14, 2024 · 0 comments
Open

1046. Last Stone Weight #175

jrmullen opened this issue Jul 14, 2024 · 0 comments

Comments

@jrmullen
Copy link
Owner

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        # Python only has a minHeap, so convert `stones` to negative numbers so we can treat it as a maxHeap
        stones = [-s for s in stones]
        heapq.heapify(stones) # Convert the input list to a heap
        while len(stones) > 1:
            # `heapPop()` pops and returns the smallest value from the heap, 
            # but since `stones` has been converted to negative numbers it is actually the largest stone
            y = heapq.heappop(stones) # `y` is the largest stone
            x = heapq.heappop(stones) # `x` is the second largest stone

            # If the weights are different, `x` is smashed and `y` becomes `x - y`
            if x != y:
                heapq.heappush(stones, y - x)
        
        # The absolute value of the final element must be returned since `stones` was converted to negative numbers
        return abs(stones[0]) if stones else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant