Maximum Value Sum by Placing Three Rooks II - Problem
You are given a m × 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.
Input & Output
Example 1 — Basic 3x3 Board
$
Input:
board = [[-3,1,1,1],[0,-3,1,1],[-3,2,1,1]]
›
Output:
4
💡 Note:
Place rooks at positions (0,2), (1,1), and (2,3). Sum = 1 + (-3) + 1 = -1. Actually, optimal is (0,1), (1,0), (2,2) giving 1 + 0 + 1 = 2. Wait, let me recalculate: (0,3)=1, (1,2)=1, (2,1)=2 gives sum = 4.
Example 2 — Negative Values
$
Input:
board = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
15
💡 Note:
Place rooks at positions (0,2), (1,1), and (2,0). Sum = 3 + 5 + 7 = 15.
Example 3 — Small Board
$
Input:
board = [[1,1],[1,1]]
›
Output:
Cannot place 3 rooks on 2x2 board
💡 Note:
Need at least 3 rows and 3 columns to place 3 non-attacking rooks.
Constraints
- m == board.length
- n == board[i].length
- 3 ≤ m, n ≤ 100
- -109 ≤ board[i][j] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Board
3x4 matrix with positive and negative values
2
Valid Placement
3 rooks on different rows and columns
3
Maximum Sum
Sum of values at selected positions
Key Takeaway
🎯 Key Insight: Fix one rook position and efficiently find optimal placements for the other two using precomputed sorted values.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code