Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e0510ec

Browse files
author
hasibulislam999
committed
Stone Game VII problem solved
1 parent a8cf3d0 commit e0510ec

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎Game Theory/1872_stone-game-viii.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Title: Stone Game VII
3+
* Description: Alice and Bob take turns playing a game, with Alice starting first.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {number[]} stones
10+
* @return {number}
11+
*/
12+
var stoneGameVIII = function (stones) {
13+
let prefix = Array(stones.length);
14+
for (let i = 0; i < stones.length; i++)
15+
prefix[i] = stones[i] + (prefix[i - 1] || 0);
16+
17+
let dp = Array(stones.length).fill(0);
18+
function game(idx) {
19+
if (dp[idx]) return dp[idx];
20+
if (idx >= stones.length) return 0;
21+
let skip = game(idx + 1);
22+
let take = prefix[idx] - skip;
23+
dp[idx] = take;
24+
// Both Alice and Bob must maximize their scores, which would maximize the difference for Alice and minimize the difference for Bob
25+
// Return the max score of either removing stones from the current idx or skipping to the next idx
26+
return !skip ? take : Math.max(skip, take);
27+
}
28+
29+
return game(1);
30+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /