Skip to content

Commit bf297af

Browse files
committed
Add solution #948
1 parent d2ccf08 commit bf297af

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-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,032 LeetCode solutions in JavaScript
1+
# 1,033 LeetCode solutions in JavaScript
22

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

@@ -757,6 +757,7 @@
757757
945|[Minimum Increment to Make Array Unique](./solutions/0945-minimum-increment-to-make-array-unique.js)|Medium|
758758
946|[Validate Stack Sequences](./solutions/0946-validate-stack-sequences.js)|Medium|
759759
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|
760761
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
761762
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|
762763
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|

solutions/0948-bag-of-tokens.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
};

0 commit comments

Comments
 (0)