☕ Java Solution | Let's learn when to use Heap (Priority Queue) 🔺
Intuition\nAs soon as we understand that we need to repeatedly get a maximum/minimum value from an array, we can use Heap (Priority Queue).\n\nYou can use Minim
# Intuition\nAs soon as we understand that we need to repeatedly get a maximum/minimum value from an array, we can use Heap (Priority Queue).\n\nYou can use Minimum Heap like this:\n***PriorityQueue<Integer> minHeap = new PriorityQueue<>();***\n\nOr you can use Maximum Heap this way:\n***PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());***\n\nAs you can see, if you want to change your heap from min to max you can simply reverse it by adding ***Comparator.reverseOrder()***;\n\nGiven this knowledge we can start implementing our solution.\n\n# Approach\n1. Initialize max heap, because we need the biggest stones.\n2. Add all stones from our initial array to the heap.\n3. While size of our heap is not equal to one we need to remove two stones and confirm if they are equal (then we will add 0 to our heap) or x != y (then we will add y - x to the heap (the biggest stone minus second one)).\n4. The last element from the heap will be our answer.\n\n# Complexity\n- Time complexity: $$O(n\\text{ }log \\text{ } n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n    public int lastStoneWeight(int[] stones) {\n        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());\n        for (int stone : stones) {\n            maxHeap.add(stone);\n        }\n        while (maxHeap.size() != 1) {\n            int y = maxHeap.remove();\n            int x = maxHeap.remove();\n            if (x == y) maxHeap.add(0);\n            if (x != y) maxHeap.add(y - x);\n        }\n        return maxHeap.peek();\n    }\n}\n```\n![4x5hdv.jpeg](https://assets.leetcode.com/users/images/d8917be9-a9ce-4b97-a3ee-8b99901cf5af_1677435627.74426.jpeg)\n
['Heap (Priority Queue)', 'Java']