-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0877-stone-game.js
More file actions
40 lines (35 loc) · 1.05 KB
/
0877-stone-game.js
File metadata and controls
40 lines (35 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Stone Game
* Time Complexity: O(N^2)
* Space Complexity: O(N^2)
*/
var stoneGame = function (piles) {
const totalPiles = piles.length;
const memoizationTable = Array(totalPiles)
.fill(null)
.map(() => Array(totalPiles).fill(0));
let indexIterator = 0;
while (indexIterator < totalPiles) {
memoizationTable[indexIterator][indexIterator] = piles[indexIterator];
indexIterator++;
}
let currentLength = 2;
while (currentLength <= totalPiles) {
let startIndex = 0;
while (startIndex <= totalPiles - currentLength) {
const endIndex = startIndex + currentLength - 1;
const optionLeft =
piles[startIndex] - memoizationTable[startIndex + 1][endIndex];
const optionRight =
piles[endIndex] - memoizationTable[startIndex][endIndex - 1];
memoizationTable[startIndex][endIndex] = Math.max(
optionLeft,
optionRight,
);
startIndex++;
}
currentLength++;
}
const finalScoreDifference = memoizationTable[0][totalPiles - 1];
return finalScoreDifference > 0;
};