File tree 2 files changed +50
-1
lines changed
2 files changed +50
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,032 LeetCode solutions in JavaScript
1
+ # 1,033 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcode.com/ ] ( https://leetcode.com/ )
4
4
757
757
945|[ Minimum Increment to Make Array Unique] ( ./solutions/0945-minimum-increment-to-make-array-unique.js ) |Medium|
758
758
946|[ Validate Stack Sequences] ( ./solutions/0946-validate-stack-sequences.js ) |Medium|
759
759
947|[ Most Stones Removed with Same Row or Column] ( ./solutions/0947-most-stones-removed-with-same-row-or-column.js ) |Medium|
760
+ 948|[ Bag of Tokens] ( ./solutions/0948-bag-of-tokens.js ) |Medium|
760
761
966|[ Vowel Spellchecker] ( ./solutions/0966-vowel-spellchecker.js ) |Medium|
761
762
970|[ Powerful Integers] ( ./solutions/0970-powerful-integers.js ) |Easy|
762
763
976|[ Largest Perimeter Triangle] ( ./solutions/0976-largest-perimeter-triangle.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 948. Bag of Tokens
3
+ * https://leetcode.com/problems/bag-of-tokens/
4
+ * Difficulty: Medium
5
+ *
6
+ * You start with an initial power of power, an initial score of 0, and a bag of tokens given as
7
+ * an integer array tokens, where each tokens[i] denotes the value of tokeni.
8
+ *
9
+ * Your goal is to maximize the total score by strategically playing these tokens. In one move,
10
+ * you can play an unplayed token in one of the two ways (but not both for the same token):
11
+ * - Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i]
12
+ * power and gaining 1 score.
13
+ * - Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power
14
+ * and losing 1 score.
15
+ *
16
+ * Return the maximum possible score you can achieve after playing any number of tokens.
17
+ */
18
+
19
+ /**
20
+ * @param {number[] } tokens
21
+ * @param {number } power
22
+ * @return {number }
23
+ */
24
+ var bagOfTokensScore = function ( tokens , power ) {
25
+ let score = 0 ;
26
+ let result = 0 ;
27
+ let left = 0 ;
28
+ let right = tokens . length - 1 ;
29
+
30
+ tokens . sort ( ( a , b ) => a - b ) ;
31
+
32
+ while ( left <= right && ( power >= tokens [ left ] || score > 0 ) ) {
33
+ while ( left <= right && power >= tokens [ left ] ) {
34
+ power -= tokens [ left ] ;
35
+ score ++ ;
36
+ left ++ ;
37
+ }
38
+ result = Math . max ( result , score ) ;
39
+
40
+ if ( left <= right && score > 0 ) {
41
+ power += tokens [ right ] ;
42
+ score -- ;
43
+ right -- ;
44
+ }
45
+ }
46
+
47
+ return result ;
48
+ } ;
You can’t perform that action at this time.
0 commit comments