Skip to content

Commit 5971704

Browse files
committed
Add solution #1046
1 parent c19ee1d commit 5971704

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,118 LeetCode solutions in JavaScript
1+
# 1,119 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -852,6 +852,7 @@
852852
1042|[Flower Planting With No Adjacent](./solutions/1042-flower-planting-with-no-adjacent.js)|Medium|
853853
1043|[Partition Array for Maximum Sum](./solutions/1043-partition-array-for-maximum-sum.js)|Medium|
854854
1044|[Longest Duplicate Substring](./solutions/1044-longest-duplicate-substring.js)|Hard|
855+
1046|[Last Stone Weight](./solutions/1046-last-stone-weight.js)|Easy|
855856
1047|[Remove All Adjacent Duplicates In String](./solutions/1047-remove-all-adjacent-duplicates-in-string.js)|Easy|
856857
1051|[Height Checker](./solutions/1051-height-checker.js)|Easy|
857858
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|

solutions/1046-last-stone-weight.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 1046. Last Stone Weight
3+
* https://leetcode.com/problems/last-stone-weight/
4+
* Difficulty: Easy
5+
*
6+
* You are given an array of integers stones where stones[i] is the weight of the ith stone.
7+
*
8+
* We are playing a game with the stones. On each turn, we choose the heaviest two stones and
9+
* smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The
10+
* result of this smash is:
11+
* - If x == y, both stones are destroyed, and
12+
* - If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
13+
*
14+
* At the end of the game, there is at most one stone left.
15+
*
16+
* Return the weight of the last remaining stone. If there are no stones left, return 0.
17+
*/
18+
19+
/**
20+
* @param {number[]} stones
21+
* @return {number}
22+
*/
23+
var lastStoneWeight = function(stones) {
24+
const heap = stones.sort((a, b) => b - a);
25+
26+
while (heap.length > 1) {
27+
const heaviest = heap.shift();
28+
const secondHeaviest = heap.shift();
29+
if (heaviest !== secondHeaviest) {
30+
heap.push(heaviest - secondHeaviest);
31+
heap.sort((a, b) => b - a);
32+
}
33+
}
34+
35+
return heap.length ? heap[0] : 0;
36+
};

0 commit comments

Comments
 (0)