Maximum Value Sum by Placing Three Rooks I - Problem

You are given an 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.

Input & Output

Example 1 — Basic 3×3 Board
$ Input: board = [[1,2,3],[4,5,6],[7,8,9]]
Output: 15
💡 Note: Place rooks at (0,0), (1,1), (2,2): values 1+5+9=15. This is optimal since rooks are on different rows and columns.
Example 2 — Negative Values
$ Input: board = [[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
Output: 4
💡 Note: Place rooks at (0,1), (1,3), (2,1): values 1+1+2=4. Avoid negative values (-3) when possible.
Example 3 — All Same Values
$ Input: board = [[5,5,5],[5,5,5],[5,5,5]]
Output: 15
💡 Note: Any valid placement gives the same sum: 5+5+5=15 since all cells have value 5.

Constraints

  • 3 ≤ m, n ≤ 100
  • -106 ≤ board[i][j] ≤ 106
  • It's guaranteed that a solution exists

Visualization

Tap to expand
Maximum Value Sum: Three Non-Attacking RooksInput Board123456789Place 3 RooksOptimal Solution123456789Positions: (0,0), (1,1), (2,2)Values: 1 + 5 + 9 = 15✓ Different rows and columnsMaximum Sum = 15
Understanding the Visualization
1
Input
3×3 chessboard with values [[1,2,3],[4,5,6],[7,8,9]]
2
Constraint
3 rooks must be on different rows AND different columns
3
Output
Maximum sum = 15 from positions (0,0)+(1,1)+(2,2) = 1+5+9
Key Takeaway
🎯 Key Insight: Rooks attack along rows and columns, so three non-attacking rooks need different rows AND different columns
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
8.9K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen