|  | 
|  | 1 | +/** | 
|  | 2 | + * Title: Can I Win | 
|  | 3 | + * Description: In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins. | 
|  | 4 | + * Author: Hasibul Islam | 
|  | 5 | + * Date: 06/05/2023 | 
|  | 6 | + */ | 
|  | 7 | + | 
|  | 8 | +/** | 
|  | 9 | + * @param {number} maxChoosableInteger | 
|  | 10 | + * @param {number} desiredTotal | 
|  | 11 | + * @return {boolean} | 
|  | 12 | + */ | 
|  | 13 | +function canIWin(maxChoosableInteger, desiredTotal) { | 
|  | 14 | + if (desiredTotal === 0) return true; | 
|  | 15 | + if ((maxChoosableInteger * (maxChoosableInteger + 1)) / 2 < desiredTotal) | 
|  | 16 | + return false; | 
|  | 17 | + | 
|  | 18 | + const initialChoices = Math.pow(2, maxChoosableInteger) - 1; | 
|  | 19 | + | 
|  | 20 | + const dp = []; | 
|  | 21 | + | 
|  | 22 | + function DP(choices, total) { | 
|  | 23 | + if (total <= 0) return false; | 
|  | 24 | + | 
|  | 25 | + if (dp[choices] !== undefined) { | 
|  | 26 | + return dp[choices]; | 
|  | 27 | + } | 
|  | 28 | + | 
|  | 29 | + let pow = 0; | 
|  | 30 | + let choicesCopy = choices; | 
|  | 31 | + | 
|  | 32 | + dp[choices] = false; | 
|  | 33 | + | 
|  | 34 | + while (choicesCopy > 0) { | 
|  | 35 | + if (choicesCopy % 2 && !DP(choices - (1 << pow), total - pow - 1)) { | 
|  | 36 | + dp[choices] = true; | 
|  | 37 | + break; | 
|  | 38 | + } | 
|  | 39 | + choicesCopy >>= 1; | 
|  | 40 | + pow++; | 
|  | 41 | + } | 
|  | 42 | + | 
|  | 43 | + return dp[choices]; | 
|  | 44 | + } | 
|  | 45 | + | 
|  | 46 | + return DP(initialChoices, desiredTotal); | 
|  | 47 | +} | 
0 commit comments