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 II INPUT 3x4 Chessboard (board) -3 1 1 1 0 -3 1 1 -3 2 1 1 0 1 2 0 1 2 3 Constraint: Rooks attack same row or column R Red = attacked cells ALGORITHM STEPS 1 Sort columns per row Keep top 3 values each row 2 Enumerate row triplets Pick 3 different rows (i,j,k) 3 Prune column conflicts Only check distinct columns 4 Track maximum sum Update best combination Top 3 Values Per Row: Row 1st 2nd 3rd 0 1 1 1 1 1 1 0 2 2 1 1 O(m^3 * 27) with pruning FINAL RESULT Optimal Rook Placement -3 1 R1 1 1 0 -3 1 R2 1 -3 2 R3 1 1 Sum Calculation: R1: board[0][1] = 1 R2: board[1][2] = 1 R3: board[2][1] = 2 Total = 1 + 1 + 2 Output: 4 OK - Maximum sum found! Key Insight: Smart enumeration reduces complexity from O(m*n)^3 to O(m^3 * 27) by keeping only the top 3 column values per row. Since rooks must be in different rows AND columns, we only need to consider the best candidates per row - at most 3 columns can be "blocked" by other rooks, so top 3 always includes optimal. TutorialsPoint - Maximum Value Sum by Placing Three Rooks II | Smart Enumeration with Pruning
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