LeetCode 1046: Last Stone Weight Solution

Master LeetCode problem 1046 (Last Stone Weight), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1046. Last Stone Weight

Problem Explanation

Explanation:

To solve this problem, we can use a max-heap (priority queue) to store the weights of the stones. We will repeatedly pop the two heaviest stones from the heap, smash them together based on the rules, and then push the resulting weight back into the heap. We will continue this process until there is at most one stone left in the heap.

Algorithm:

  1. Create a max-heap to store the weights of the stones.
  2. Insert all the stone weights into the max-heap.
  3. While there are at least two stones in the heap, do the following:
    • Pop the two heaviest stones from the heap.
    • If they have different weights, calculate the new weight and push it back into the heap.
  4. If there is only one stone left in the heap, return its weight. If the heap is empty, return 0.

Time Complexity:

The time complexity of this algorithm is O(n log n) where n is the number of stones, as we perform heap operations for each stone.

Space Complexity:

The space complexity is O(n) due to the max-heap storing the weights of the stones.

: :

Solution Code

import java.util.PriorityQueue;

class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
        
        for (int stone : stones) {
            maxHeap.offer(stone);
        }
        
        while (maxHeap.size() > 1) {
            int y = maxHeap.poll();
            int x = maxHeap.poll();
            
            if (x != y) {
                maxHeap.offer(y - x);
            }
        }
        
        return maxHeap.isEmpty() ? 0 : maxHeap.peek();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1046 (Last Stone Weight)?

This page provides optimized solutions for LeetCode problem 1046 (Last Stone Weight) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1046 (Last Stone Weight)?

The time complexity for LeetCode 1046 (Last Stone Weight) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1046 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1046 in Java, C++, or Python.

Back to LeetCode Solutions