Skip to content

Commit fe97771

Browse files
author
hasibulislam999
committed
Stone Game V problems solved
1 parent aeda7fc commit fe97771

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Game Theory/1563_stone-game-v.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Title: Stone Game V
3+
* Description: There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {number[]} stoneValue
10+
* @return {number}
11+
*/
12+
var stoneGameV = function (stones) {
13+
let bestAns = 0;
14+
let stoneSum = stones.reduce((sum, current) => {
15+
return sum + current;
16+
}, 0);
17+
18+
function splitAndAdd(stoneSum, ans, leftBound, rightBound) {
19+
if (rightBound === leftBound) {
20+
return ans;
21+
}
22+
23+
if (rightBound - leftBound === 1) {
24+
return ans + Math.min(stones[leftBound], stones[rightBound]);
25+
}
26+
let bestSoFar = 0;
27+
let leftSum = 0;
28+
let rightSum = stoneSum;
29+
for (let i = leftBound; i <= rightBound; i++) {
30+
leftSum += stones[i];
31+
rightSum -= stones[i];
32+
33+
if (2 * Math.min(leftSum, rightSum) + ans < bestAns) {
34+
continue;
35+
}
36+
if (leftSum === rightSum) {
37+
bestSoFar = Math.max(
38+
splitAndAdd(leftSum, ans + leftSum, leftBound, i),
39+
bestSoFar
40+
);
41+
bestSoFar = Math.max(
42+
splitAndAdd(rightSum, ans + rightSum, i + 1, rightBound),
43+
bestSoFar
44+
);
45+
} else {
46+
leftSum > rightSum
47+
? (bestSoFar = Math.max(
48+
splitAndAdd(rightSum, ans + rightSum, i + 1, rightBound),
49+
bestSoFar
50+
))
51+
: (bestSoFar = Math.max(
52+
splitAndAdd(leftSum, ans + leftSum, leftBound, i),
53+
bestSoFar
54+
));
55+
}
56+
}
57+
58+
bestAns = Math.max(bestAns, bestSoFar);
59+
return bestSoFar;
60+
}
61+
62+
let ans = splitAndAdd(stoneSum, 0, 0, stones.length - 1);
63+
return ans;
64+
};

0 commit comments

Comments
 (0)