Last Stone Weight
easyHeap / Priority Queue+10 XPTime limit 2s
You have stones with positive weights. Each turn, take the two heaviest stones x ≥ y and smash them: if x = y both are destroyed; otherwise the y stone is destroyed and the other becomes x − y. Continue until at most one stone is left. Print its weight, or 0 if none is left.
Input:
- line 1:
n - line 2:
nweights
Output: the weight of the last stone, or 0.
Constraints: 1 ≤ n ≤ 10⁵, 1 ≤ weight ≤ 10⁹.
Think about it: sorting every turn is O(n² log n). A max-heap gives the two heaviest in O(log n) each. (Python's heapq is a min-heap — push negated weights.)
Sample input 1
6 2 7 4 1 8 1
Sample output 1
1
Sample input 2
1 1
Sample output 2
1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).