Data Structures19 sections · 729 units
Open in Course

Last Stone - Implementation

Complete solution

Here's the solution:

function lastStoneWeight(stones)
    heap := max-heap containing all stones

    while size of heap > 1
        y := extract max from heap
        x := extract max from heap
        if y > x
            insert (y - x) into heap

    if heap is empty
        return 0
    return extract max from heap

Time: O(nlogn)O(n \log n). Space: O(n)O(n).