Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
The game ends when there is only one stone remaining. Alice's score is initially zero.
Return the maximum score that Alice can obtain.
Example 1:
Input: stoneValue = [6,2,3,4,5,5] Output: 18 Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11. In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5). The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.
Example 2:
Input: stoneValue = [7,7,7,7,7,7,7] Output: 28
Example 3:
Input: stoneValue = [4] Output: 0
Constraints:
1 <= stoneValue.length <= 5001 <= stoneValue[i] <= 106Problem summary: There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's score is initially zero. Return the maximum score that Alice can obtain.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming
[6,2,3,4,5,5]
[7,7,7,7,7,7,7]
[4]
stone-game)stone-game-ii)stone-game-iii)stone-game-iv)stone-game-vi)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1563: Stone Game V
class Solution {
private int n;
private int[] s;
private int[] nums;
private Integer[][] f;
public int stoneGameV(int[] stoneValue) {
n = stoneValue.length;
s = new int[n + 1];
nums = stoneValue;
f = new Integer[n][n];
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums[i - 1];
}
return dfs(0, n - 1);
}
private int dfs(int i, int j) {
if (i >= j) {
return 0;
}
if (f[i][j] != null) {
return f[i][j];
}
int ans = 0, l = 0, r = s[j + 1] - s[i];
for (int k = i; k < j; ++k) {
l += nums[k];
r -= nums[k];
if (l < r) {
if (ans > l * 2) {
continue;
}
ans = Math.max(ans, l + dfs(i, k));
} else if (l > r) {
if (ans > r * 2) {
break;
}
ans = Math.max(ans, r + dfs(k + 1, j));
} else {
ans = Math.max(ans, Math.max(l + dfs(i, k), r + dfs(k + 1, j)));
}
}
return f[i][j] = ans;
}
}
// Accepted solution for LeetCode #1563: Stone Game V
func stoneGameV(stoneValue []int) int {
n := len(stoneValue)
s := make([]int, n+1)
for i, x := range stoneValue {
s[i+1] = s[i] + x
}
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(int, int) int
dfs = func(i, j int) int {
if i >= j {
return 0
}
if f[i][j] != -1 {
return f[i][j]
}
ans, l, r := 0, 0, s[j+1]-s[i]
for k := i; k < j; k++ {
l += stoneValue[k]
r -= stoneValue[k]
if l < r {
if ans > l*2 {
continue
}
ans = max(ans, dfs(i, k)+l)
} else if l > r {
if ans > r*2 {
break
}
ans = max(ans, dfs(k+1, j)+r)
} else {
ans = max(ans, max(dfs(i, k), dfs(k+1, j))+l)
}
}
f[i][j] = ans
return ans
}
return dfs(0, n-1)
}
# Accepted solution for LeetCode #1563: Stone Game V
def max(a: int, b: int) -> int:
return a if a > b else b
class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= j:
return 0
ans = l = 0
r = s[j + 1] - s[i]
for k in range(i, j):
l += stoneValue[k]
r -= stoneValue[k]
if l < r:
if ans >= l * 2:
continue
ans = max(ans, l + dfs(i, k))
elif l > r:
if ans >= r * 2:
break
ans = max(ans, r + dfs(k + 1, j))
else:
ans = max(ans, max(l + dfs(i, k), r + dfs(k + 1, j)))
return ans
s = list(accumulate(stoneValue, initial=0))
return dfs(0, len(stoneValue) - 1)
// Accepted solution for LeetCode #1563: Stone Game V
struct Solution;
use std::collections::HashMap;
impl Solution {
fn stone_game_v(stone_value: Vec<i32>) -> i32 {
let mut memo: HashMap<(usize, usize), i32> = HashMap::new();
let n = stone_value.len();
Self::dp(0, n, &mut memo, &stone_value)
}
fn dp(
start: usize,
end: usize,
memo: &mut HashMap<(usize, usize), i32>,
stones: &[i32],
) -> i32 {
if end - start < 2 {
return 0;
}
if let Some(&res) = memo.get(&(start, end)) {
return res;
}
let mut left = 0;
let mut right = stones[start..end].iter().sum::<i32>();
let mut res = 0;
for i in start..end {
left += stones[i];
right -= stones[i];
if left > right {
res = res.max(right + Self::dp(i + 1, end, memo, stones));
continue;
}
if left < right {
res = res.max(left + Self::dp(start, i + 1, memo, stones));
continue;
}
res = res.max(left + Self::dp(start, i + 1, memo, stones));
res = res.max(right + Self::dp(i + 1, end, memo, stones));
}
memo.insert((start, end), res);
res
}
}
#[test]
fn test() {
let stone_value = vec![6, 2, 3, 4, 5, 5];
let res = 18;
assert_eq!(Solution::stone_game_v(stone_value), res);
}
// Accepted solution for LeetCode #1563: Stone Game V
function stoneGameV(stoneValue: number[]): number {
const n = stoneValue.length;
const s: number[] = Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
s[i + 1] = s[i] + stoneValue[i];
}
const f: number[][] = Array.from({ length: n }, () => Array(n).fill(-1));
const dfs = (i: number, j: number): number => {
if (i >= j) {
return 0;
}
if (f[i][j] !== -1) {
return f[i][j];
}
let [ans, l, r] = [0, 0, s[j + 1] - s[i]];
for (let k = i; k < j; ++k) {
l += stoneValue[k];
r -= stoneValue[k];
if (l < r) {
if (ans > l * 2) {
continue;
}
ans = Math.max(ans, l + dfs(i, k));
} else if (l > r) {
if (ans > r * 2) {
break;
}
ans = Math.max(ans, r + dfs(k + 1, j));
} else {
ans = Math.max(ans, l + dfs(i, k), r + dfs(k + 1, j));
}
}
return (f[i][j] = ans);
};
return dfs(0, n - 1);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.