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.
You are given a m x n 2D array board representing a chessboard, where board[i][j] represents the value of the cell (i, j).
Rooks in the same row or column attack each other. You need to place three rooks on the chessboard such that the rooks do not attack each other.
Return the maximum sum of the cell values on which the rooks are placed.
Example 1:
Input: board = [[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
Output: 4
Explanation:
We can place the rooks in the cells (0, 2), (1, 3), and (2, 1) for a sum of 1 + 1 + 2 = 4.
Example 2:
Input: board = [[1,2,3],[4,5,6],[7,8,9]]
Output: 15
Explanation:
We can place the rooks in the cells (0, 0), (1, 1), and (2, 2) for a sum of 1 + 5 + 9 = 15.
Example 3:
Input: board = [[1,1,1],[1,1,1],[1,1,1]]
Output: 3
Explanation:
We can place the rooks in the cells (0, 2), (1, 1), and (2, 0) for a sum of 1 + 1 + 1 = 3.
Constraints:
3 <= m == board.length <= 5003 <= n == board[i].length <= 500-109 <= board[i][j] <= 109Problem summary: You are given a m x n 2D array board representing a chessboard, where board[i][j] represents the value of the cell (i, j). Rooks in the same row or column attack each other. You need to place three rooks on the chessboard such that the rooks do not attack each other. Return the maximum sum of the cell values on which the rooks are placed.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
[[1,2,3],[4,5,6],[7,8,9]]
[[1,1,1],[1,1,1],[1,1,1]]
available-captures-for-rook)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
class Solution {
// Same as 3256. Maximum Value Sum by Placing Three Rooks I
public long maximumValueSum(int[][] board) {
final int m = board.length;
final int n = board[0].length;
long ans = Long.MIN_VALUE;
List<int[]>[] rows = new ArrayList[m];
List<int[]>[] cols = new ArrayList[n];
Set<int[]> rowSet = new HashSet<>();
Set<int[]> colSet = new HashSet<>();
Set<int[]> boardSet = new HashSet<>();
for (int i = 0; i < m; ++i)
rows[i] = new ArrayList<>();
for (int j = 0; j < n; ++j)
cols[j] = new ArrayList<>();
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
int[] cell = new int[] {board[i][j], i, j};
rows[i].add(cell);
cols[j].add(cell);
}
Comparator<int[]> comparator = Comparator.comparingInt(a -> - a[0]);
for (List<int[]> row : rows) {
row.sort(comparator);
rowSet.addAll(row.subList(0, Math.min(3, row.size())));
}
for (List<int[]> col : cols) {
col.sort(comparator);
colSet.addAll(col.subList(0, Math.min(3, col.size())));
}
boardSet.addAll(rowSet);
boardSet.retainAll(colSet);
// At least 9 positions are required on the board to place 3 rooks such that
// none can attack another.
List<int[]> topNine = new ArrayList<>(boardSet);
topNine.sort(comparator);
topNine = topNine.subList(0, Math.min(9, topNine.size()));
for (int i = 0; i < topNine.size(); ++i)
for (int j = i + 1; j < topNine.size(); ++j)
for (int k = j + 1; k < topNine.size(); ++k) {
int[] t1 = topNine.get(i);
int[] t2 = topNine.get(j);
int[] t3 = topNine.get(k);
if (t1[1] == t2[1] || t1[1] == t3[1] || t2[1] == t3[1] || //
t1[2] == t2[2] || t1[2] == t3[2] || t2[2] == t3[2])
continue;
ans = Math.max(ans, (long) t1[0] + t2[0] + t3[0]);
}
return ans;
}
}
// Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
package main
import "math"
// https://space.bilibili.com/206214
func maximumValueSum(board [][]int) int64 {
m, n := len(board), len(board[0])
// rid 为反向边在邻接表中的下标
type neighbor struct{ to, rid, cap, cost int }
g := make([][]neighbor, m+n+3)
addEdge := func(from, to, cap, cost int) {
g[from] = append(g[from], neighbor{to, len(g[to]), cap, cost})
g[to] = append(g[to], neighbor{from, len(g[from]) - 1, 0, -cost})
}
R := m + n
C := m + n + 1
S := m + n + 2
for i, row := range board {
for j, x := range row {
addEdge(i, m+j, 1, -x)
}
addEdge(R, i, 1, 0)
}
for j := range board[0] {
addEdge(m+j, C, 1, 0)
}
addEdge(S, R, 3, 0) // 把 3 改成 k 可以支持 k 个车
// 下面是费用流模板
dis := make([]int, len(g))
type vi struct{ v, i int }
fa := make([]vi, len(g))
inQ := make([]bool, len(g))
spfa := func() bool {
for i := range dis {
dis[i] = math.MaxInt
}
dis[S] = 0
inQ[S] = true
q := []int{S}
for len(q) > 0 {
v := q[0]
q = q[1:]
inQ[v] = false
for i, e := range g[v] {
if e.cap == 0 {
continue
}
w := e.to
newD := dis[v] + e.cost
if newD < dis[w] {
dis[w] = newD
fa[w] = vi{v, i}
if !inQ[w] {
inQ[w] = true
q = append(q, w)
}
}
}
}
// 循环结束后所有 inQ[v] 都为 false,无需重置
return dis[C] < math.MaxInt
}
minCost := 0
for spfa() {
minF := math.MaxInt
for v := C; v != S; {
p := fa[v]
minF = min(minF, g[p.v][p.i].cap)
v = p.v
}
for v := C; v != S; {
p := fa[v]
e := &g[p.v][p.i]
e.cap -= minF
g[v][e.rid].cap += minF
v = p.v
}
minCost += dis[C] * minF
}
return int64(-minCost)
}
func maximumValueSum2(board [][]int) int64 {
m := len(board)
type pair struct{ x, j int }
suf := make([][3]pair, m)
p := [3]pair{} // 最大、次大、第三大
for i := range p {
p[i].x = math.MinInt
}
update := func(row []int) {
for j, x := range row {
if x > p[0].x {
if p[0].j != j { // 如果相等,仅更新最大
if p[1].j != j { // 如果相等,仅更新最大和次大
p[2] = p[1]
}
p[1] = p[0]
}
p[0] = pair{x, j}
} else if x > p[1].x && j != p[0].j {
if p[1].j != j { // 如果相等,仅更新次大
p[2] = p[1]
}
p[1] = pair{x, j}
} else if x > p[2].x && j != p[0].j && j != p[1].j {
p[2] = pair{x, j}
}
}
}
for i := m - 1; i > 1; i-- {
update(board[i])
suf[i] = p
}
ans := math.MinInt
for i := range p {
p[i].x = math.MinInt // 重置,计算 pre
}
for i, row := range board[:m-2] {
update(row)
for j, x := range board[i+1] { // 第二个车
for _, p := range p { // 第一个车
if p.j == j {
continue
}
for _, q := range suf[i+2] { // 第三个车
if q.j != j && q.j != p.j { // 没有同列的车
ans = max(ans, p.x+x+q.x)
break
}
}
}
}
}
return int64(ans)
}
# Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
class Solution:
# Same as 3256. Maximum Value Sum by Placing Three Rooks I
def maximumValueSum(self, board: list[list[int]]) -> int:
rows = [heapq.nlargest(3, [(val, i, j)
for j, val in enumerate(row)])
for i, row in enumerate(board)]
cols = [heapq.nlargest(3, [(val, i, j)
for i, val in enumerate(col)])
for j, col in enumerate(zip(*board))]
topNine = heapq.nlargest(9,
set(itertools.chain(*rows)) &
set(itertools.chain(*cols)))
return max(
(val1 + val2 + val3 for
(val1, i1, j1),
(val2, i2, j2),
(val3, i3, j3) in (itertools.combinations(topNine, 3))
if len({i1, i2, i3}) == 3 and len({j1, j2, j3}) == 3))
// Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
// class Solution {
// // Same as 3256. Maximum Value Sum by Placing Three Rooks I
// public long maximumValueSum(int[][] board) {
// final int m = board.length;
// final int n = board[0].length;
// long ans = Long.MIN_VALUE;
// List<int[]>[] rows = new ArrayList[m];
// List<int[]>[] cols = new ArrayList[n];
// Set<int[]> rowSet = new HashSet<>();
// Set<int[]> colSet = new HashSet<>();
// Set<int[]> boardSet = new HashSet<>();
//
// for (int i = 0; i < m; ++i)
// rows[i] = new ArrayList<>();
//
// for (int j = 0; j < n; ++j)
// cols[j] = new ArrayList<>();
//
// for (int i = 0; i < m; ++i)
// for (int j = 0; j < n; ++j) {
// int[] cell = new int[] {board[i][j], i, j};
// rows[i].add(cell);
// cols[j].add(cell);
// }
//
// Comparator<int[]> comparator = Comparator.comparingInt(a -> - a[0]);
//
// for (List<int[]> row : rows) {
// row.sort(comparator);
// rowSet.addAll(row.subList(0, Math.min(3, row.size())));
// }
//
// for (List<int[]> col : cols) {
// col.sort(comparator);
// colSet.addAll(col.subList(0, Math.min(3, col.size())));
// }
//
// boardSet.addAll(rowSet);
// boardSet.retainAll(colSet);
//
// // At least 9 positions are required on the board to place 3 rooks such that
// // none can attack another.
// List<int[]> topNine = new ArrayList<>(boardSet);
// topNine.sort(comparator);
// topNine = topNine.subList(0, Math.min(9, topNine.size()));
//
// for (int i = 0; i < topNine.size(); ++i)
// for (int j = i + 1; j < topNine.size(); ++j)
// for (int k = j + 1; k < topNine.size(); ++k) {
// int[] t1 = topNine.get(i);
// int[] t2 = topNine.get(j);
// int[] t3 = topNine.get(k);
// if (t1[1] == t2[1] || t1[1] == t3[1] || t2[1] == t3[1] || //
// t1[2] == t2[2] || t1[2] == t3[2] || t2[2] == t3[2])
// continue;
// ans = Math.max(ans, (long) t1[0] + t2[0] + t3[0]);
// }
//
// return ans;
// }
// }
// Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3257: Maximum Value Sum by Placing Three Rooks II
// class Solution {
// // Same as 3256. Maximum Value Sum by Placing Three Rooks I
// public long maximumValueSum(int[][] board) {
// final int m = board.length;
// final int n = board[0].length;
// long ans = Long.MIN_VALUE;
// List<int[]>[] rows = new ArrayList[m];
// List<int[]>[] cols = new ArrayList[n];
// Set<int[]> rowSet = new HashSet<>();
// Set<int[]> colSet = new HashSet<>();
// Set<int[]> boardSet = new HashSet<>();
//
// for (int i = 0; i < m; ++i)
// rows[i] = new ArrayList<>();
//
// for (int j = 0; j < n; ++j)
// cols[j] = new ArrayList<>();
//
// for (int i = 0; i < m; ++i)
// for (int j = 0; j < n; ++j) {
// int[] cell = new int[] {board[i][j], i, j};
// rows[i].add(cell);
// cols[j].add(cell);
// }
//
// Comparator<int[]> comparator = Comparator.comparingInt(a -> - a[0]);
//
// for (List<int[]> row : rows) {
// row.sort(comparator);
// rowSet.addAll(row.subList(0, Math.min(3, row.size())));
// }
//
// for (List<int[]> col : cols) {
// col.sort(comparator);
// colSet.addAll(col.subList(0, Math.min(3, col.size())));
// }
//
// boardSet.addAll(rowSet);
// boardSet.retainAll(colSet);
//
// // At least 9 positions are required on the board to place 3 rooks such that
// // none can attack another.
// List<int[]> topNine = new ArrayList<>(boardSet);
// topNine.sort(comparator);
// topNine = topNine.subList(0, Math.min(9, topNine.size()));
//
// for (int i = 0; i < topNine.size(); ++i)
// for (int j = i + 1; j < topNine.size(); ++j)
// for (int k = j + 1; k < topNine.size(); ++k) {
// int[] t1 = topNine.get(i);
// int[] t2 = topNine.get(j);
// int[] t3 = topNine.get(k);
// if (t1[1] == t2[1] || t1[1] == t3[1] || t2[1] == t3[1] || //
// t1[2] == t2[2] || t1[2] == t3[2] || t2[2] == t3[2])
// continue;
// ans = Math.max(ans, (long) t1[0] + t2[0] + t3[0]);
// }
//
// return ans;
// }
// }
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: 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.