Skip to content

Commit 66142d3

Browse files
committedMar 1, 2025
Add solution #464
1 parent cef3ec5 commit 66142d3

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,7 @@
372372
461|[Hamming Distance](./0461-hamming-distance.js)|Easy|
373373
462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium|
374374
463|[Island Perimeter](./0463-island-perimeter.js)|Medium|
375+
464|[Can I Win](./0464-can-i-win.js)|Medium|
375376
472|[Concatenated Words](./0472-concatenated-words.js)|Hard|
376377
476|[Number Complement](./0476-number-complement.js)|Easy|
377378
482|[License Key Formatting](./0482-license-key-formatting.js)|Easy|

‎solutions/0464-can-i-win.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 464. Can I Win
3+
* https://leetcode.com/problems/can-i-win/
4+
* Difficulty: Medium
5+
*
6+
* In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10.
7+
* The player who first causes the running total to reach or exceed 100 wins.
8+
*
9+
* What if we change the game so that players cannot re-use integers?
10+
*
11+
* For example, two players might take turns drawing from a common pool of numbers from 1 to 15
12+
* without replacement until they reach a total >= 100.
13+
*
14+
* Given two integers maxChoosableInteger and desiredTotal, return true if the first player to
15+
* move can force a win, otherwise, return false. Assume both players play optimally.
16+
*/
17+
18+
/**
19+
* @param {number} maxChoosableInteger
20+
* @param {number} desiredTotal
21+
* @return {boolean}
22+
*/
23+
var canIWin = function(maxChoosableInteger, desiredTotal) {
24+
const memo = new Map();
25+
const sum = (maxChoosableInteger * (maxChoosableInteger + 1)) / 2;
26+
27+
if (desiredTotal <= 0) return true;
28+
if (sum < desiredTotal) return false;
29+
30+
return check(0, desiredTotal);
31+
32+
function check(state, remaining) {
33+
if (remaining <= 0) return false;
34+
35+
const key = state.toString();
36+
if (memo.has(key)) return memo.get(key);
37+
38+
for (let i = 1; i <= maxChoosableInteger; i++) {
39+
const mask = 1 << i;
40+
if (!(state & mask) && (i >= remaining || !check(state | mask, remaining - i))) {
41+
memo.set(key, true);
42+
return true;
43+
}
44+
}
45+
46+
memo.set(key, false);
47+
return false;
48+
}
49+
};

0 commit comments

Comments
 (0)
Please sign in to comment.