Leetcode 1046: Last Stone Weight

grid47
grid47
Exploring patterns and algorithms
Jul 25, 2024 6 min read

In this problem, we have an array of integers representing stones. Each stone has a weight, and on each turn, we choose the two heaviest stones, smash them together, and apply the following rules: If the two stones have the same weight, both are destroyed. If they have different weights, the stone with the smaller weight is destroyed, and the stone with the larger weight gets reduced by the smaller stone’s weight. The process continues until at most one stone remains. Your task is to return the weight of the last remaining stone. If no stones are left, return 0.
Problem
Approach
Steps
Complexity
Input: You are given an array `stones`, where each element represents the weight of a stone.
Example: Input: stones = [5, 10, 2, 6]
Constraints:
• 1 <= stones.length <= 30
• 1 <= stones[i] <= 1000
Output: Return the weight of the last remaining stone after applying the smash rules described above. If there are no stones left, return 0.
Example: Output: 4
Constraints:
• The result will always fit within a 32-bit integer.
Goal: The goal is to simulate the process of smashing stones and compute the weight of the last remaining stone.
Steps:
• 1. Use a priority queue (max heap) to efficiently find and remove the two heaviest stones.
• 2. Continue the process of smashing the two heaviest stones until one or no stones remain.
• 3. If there is one stone left, return its weight. If no stones remain, return 0.
Goal: The array contains at least one stone, and at most 30 stones are allowed. Stone weights range between 1 and 1000.
Steps:
• 1 <= stones.length <= 30
• 1 <= stones[i] <= 1000
Assumptions:
• At least one stone will always be present.
• Stone weights will be positive integers.
Input: Input: stones = [5, 10, 2, 6]
Explanation: We start with the stones [5, 10, 2, 6]. First, we smash 10 and 6, resulting in 4 (10 - 6). The new array is [5, 2, 4]. Next, we smash 5 and 4, resulting in 1 (5 - 4). The new array is [2, 1]. Finally, we smash 2 and 1, resulting in 1. The last stone remaining is 1.

Input: Input: stones = [3, 7, 9, 5]
Explanation: We start with the stones [3, 7, 9, 5]. First, we smash 9 and 7, resulting in 2 (9 - 7). The new array is [3, 5, 2]. Next, we smash 5 and 3, resulting in 2 (5 - 3). The new array is [2, 2]. Finally, we smash 2 and 2, resulting in 0. The last stone remaining is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus