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 by Placing Three Rooks INPUT 1 2 3 4 5 6 7 8 9 0 1 2 0 1 2 board = [[1,2,3], [4,5,6], [7,8,9]] 3x3 chessboard Place 3 non-attacking rooks ALGORITHM STEPS 1 Sort Each Row Keep top 3 values per row 2 Select 3 Different Rows Each rook on unique row 3 Assign Columns No two rooks same column 4 Maximize Sum Try all valid combinations Optimal Selection: Row 0: col 2 --> value 3 Row 1: col 1 --> value 5 Row 2: col 0 --> value 7 Sum = 3 + 5 + 7 = 15 FINAL RESULT 3 5 7 1 2 4 6 8 9 Output: 15 Rooks at (0,2), (1,1), (2,0) No attacks possible OK - Valid placement! Key Insight: For 3 rooks on different rows and columns, we need to select one cell from each row such that all columns are distinct. By keeping only the top 3 values per row, we reduce the search space while guaranteeing we find the optimal solution. Time: O(m * n log n). TutorialsPoint - Maximum Value Sum by Placing Three Rooks I | Row Selection with Column Optimization
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