Skip to content

Commit 0b782e4

Browse files
author
hasibulislam999
committed
Stone Game II problem solved
1 parent b0778fa commit 0b782e4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Game Theory/1140_stone-game-ii.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Title: Stone Game II
3+
* Description: Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {number[]} piles
10+
* @return {number}
11+
*/
12+
var stoneGameII = function (piles) {
13+
const length = piles.length;
14+
const dp = [...Array(length + 1).fill(null)].map((_) =>
15+
Array(length + 1).fill(0)
16+
);
17+
const sufsum = new Array(length + 1).fill(0);
18+
for (let i = length - 1; i >= 0; i--) {
19+
sufsum[i] = sufsum[i + 1] + piles[i];
20+
}
21+
for (let i = 0; i <= length; i++) {
22+
dp[i][length] = sufsum[i];
23+
}
24+
for (let i = length - 1; i >= 0; i--) {
25+
for (let j = length - 1; j >= 1; j--) {
26+
for (let X = 1; X <= 2 * j && i + X <= length; X++) {
27+
dp[i][j] = Math.max(dp[i][j], sufsum[i] - dp[i + X][Math.max(j, X)]);
28+
}
29+
}
30+
}
31+
return dp[0][1];
32+
};

0 commit comments

Comments
 (0)