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
Maximum Value Sum by Placing Three Rooks-31110-311-3211Valid Placement: Rooks at (0,1), (1,0), (2,2)No two rooks share the same row or columnMaximum Sum: 1 + 0 + 1 = 2
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.
Asked in
Google 25 Microsoft 18 Amazon 15
8.5K Views
Medium Frequency
~35 min Avg. Time
342 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