File tree 2 files changed +39
-1
lines changed
2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,120 LeetCode solutions in JavaScript
1
+ # 1,121 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
855
855
1046|[ Last Stone Weight] ( ./solutions/1046-last-stone-weight.js ) |Easy|
856
856
1047|[ Remove All Adjacent Duplicates In String] ( ./solutions/1047-remove-all-adjacent-duplicates-in-string.js ) |Easy|
857
857
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|
858
859
1051|[ Height Checker] ( ./solutions/1051-height-checker.js ) |Easy|
859
860
1071|[ Greatest Common Divisor of Strings] ( ./solutions/1071-greatest-common-divisor-of-strings.js ) |Easy|
860
861
1072|[ Flip Columns For Maximum Number of Equal Rows] ( ./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments