Problem
You are given a 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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
3 <= m == board.length <= 500
3 <= n == board[i].length <= 500
-109 <= board[i][j] <= 10^9
Solution
Method 1 – Dynamic Programming with Bitmask
Intuition
Instead of brute-forcing all placements, we use dynamic programming with bitmasking to efficiently track which rows and columns are used. For each combination of three rows and three columns, we try all permutations and use DP to avoid redundant calculations.
Approach
- For all combinations of three distinct rows and three distinct columns:
- For each permutation of columns, sum the values at (row[i], col[perm[i]]).
- Track the maximum sum found.
- Use memoization to avoid recalculating for the same set of rows/columns.
- Return the maximum sum.
Complexity
- ⏰ Time complexity:
O(m^3 * n^3 * 6)
— All combinations of rows and columns, and all permutations (6) for each. - 🧺 Space complexity:
O(1)
— Only variables for tracking maximum sum.
C++
|
|
Go
|
|
Java
|
|
Kotlin
|
|
Python
|
|
Rust
|
|
TypeScript
|
|