/**
* Problem: LeetCode 1872 - Stone Game VIII
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int stoneGameVIII(int[] stones) {
int n = stones.length;
long[] prefix = new long[n];
prefix[0] = stones[0];
for (int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + stones[i];
}
// dp represents the best score difference the current player can achieve
// starting from the state where the "cut" is at index i (i.e., first i+1 stones merged)
long dp = prefix[n - 1];
for (int i = n - 2; i >= 1; i--) {
dp = Math.max(dp, prefix[i] - dp);
}
return (int) dp;
}
}
"""
Problem: LeetCode 1872 - Stone Game VIII
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def stoneGameVIII(self, stones: List[int]) -> int:
n = len(stones)
prefix = [0] * n
prefix[0] = stones[0]
for i in range(1, n):
prefix[i] = prefix[i - 1] + stones[i]
# dp represents the best score difference achievable starting from index i
dp = prefix[-1]
for i in range(n - 2, 0, -1):
dp = max(dp, prefix[i] - dp)
return dp
/**
* Problem: LeetCode 1872 - Stone Game VIII
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 1872 - Stone Game VIII
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int stoneGameVIII(vector<int>& stones) {
int n = stones.size();
vector<long long> prefix(n);
prefix[0] = stones[0];
for (int i = 1; i < n; ++i) {
prefix[i] = prefix[i - 1] + stones[i];
}
// dp represents the best score difference achievable starting from index i
long long dp = prefix[n - 1];
for (int i = n - 2; i >= 1; --i) {
dp = max(dp, prefix[i] - dp);
}
return static_cast<int>(dp);
}
};
/**
* Problem: LeetCode 1872 - Stone Game VIII
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var stoneGameVIII = function(stones) {
const n = stones.length;
const prefix = new Array(n);
prefix[0] = stones[0];
for (let i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + stones[i];
}
// dp represents the best score difference achievable starting from index i
let dp = prefix[n - 1];
for (let i = n - 2; i >= 1; i--) {
dp = Math.max(dp, prefix[i] - dp);
}
return dp;
};
TIME COMPLEXITY
O(N)
SPACE COMPLEXITY
O(N)
TOPICS
Array
Dynamic Programming
Game Theory
Math
Prefix Sum