Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d3d84bd

Browse files
committedApr 2, 2025
Add solution #1049
1 parent 2a9e0f7 commit d3d84bd

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-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,120 LeetCode solutions in JavaScript
1+
# 1,121 LeetCode solutions in JavaScript
22

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

@@ -855,6 +855,7 @@
855855
1046|[Last Stone Weight](./solutions/1046-last-stone-weight.js)|Easy|
856856
1047|[Remove All Adjacent Duplicates In String](./solutions/1047-remove-all-adjacent-duplicates-in-string.js)|Easy|
857857
1048|[Longest String Chain](./solutions/1048-longest-string-chain.js)|Medium|
858+
1049|[Last Stone Weight II](./solutions/1049-last-stone-weight-ii.js)|Medium|
858859
1051|[Height Checker](./solutions/1051-height-checker.js)|Easy|
859860
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
860861
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 1049. Last Stone Weight II
3+
* https://leetcode.com/problems/last-stone-weight-ii/
4+
* Difficulty: Medium
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 any two stones and smash
9+
* them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
10+
* - If x == y, both stones are destroyed, and
11+
* - If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
12+
*
13+
* At the end of the game, there is at most one stone left.
14+
*
15+
* Return the smallest possible weight of the left stone. If there are no stones left, return 0.
16+
*/
17+
18+
/**
19+
* @param {number[]} stones
20+
* @return {number}
21+
*/
22+
var lastStoneWeightII = function(stones) {
23+
const totalSum = stones.reduce((sum, weight) => sum + weight, 0);
24+
const target = Math.floor(totalSum / 2);
25+
const set = new Set([0]);
26+
27+
for (const stone of stones) {
28+
const prev = new Set(set);
29+
for (const sum of prev) {
30+
if (sum + stone <= target) {
31+
set.add(sum + stone);
32+
}
33+
}
34+
}
35+
36+
return totalSum - 2 * Math.max(...set);
37+
};

0 commit comments

Comments
 (0)
Please sign in to comment.