Maximum Value Sum by Placing Three Rooks II Problem
Description
LeetCode Problem 3257.
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.
Example 1:
Input: board = [[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
Output: 4
Explanation:

We can place the rooks in the cells (0, 2), (1, 3), and (2, 1) for a sum of 1 + 1 + 2 = 4.
Example 2:
Input: board = [[1,2,3],[4,5,6],[7,8,9]]
Output: 15
Explanation:
We can place the rooks in the cells (0, 0), (1, 1), and (2, 2) for a sum of 1 + 5 + 9 = 15.
Example 3:
Input: board = [[1,1,1],[1,1,1],[1,1,1]]
Output: 3
Explanation:
We can place the rooks in the cells (0, 2), (1, 1), and (2, 0) for a sum of 1 + 1 + 1 = 3.
Constraints:
3 <= m == board.length <= 5003 <= n == board[i].length <= 500-10^9 <= board[i][j] <= 10^9
Solution
Approach: Keep Only Top Candidates
Checking every triple of cells is far too slow, but only a few cells can matter. If a rook sits on a cell that is not among the 3 largest of its row, the other two rooks can block at most 2 of those 3 columns, so the rook can move to a larger free cell in the same row without hurting the sum. The same argument works for columns.
So keep the 3 largest cells of each row, then among those keep the 3 largest of each column. Sort the survivors by value. By the same exchange argument, an optimal placement exists among the 20 largest survivors. Try all triples of these cells that use distinct rows and columns and take the best sum. This is the Part I solution; it is fast enough for boards up to 500 x 500 because it never looks at more than 3m candidates.
Complexity: O(m * n) time to pick the row candidates (plus sorting at most 3m cells), then a constant amount of work for the triples. O(m) extra space.
class Solution:
def maximumValueSum(self, board: List[List[int]]) -> int:
n = len(board[0])
cand = []
for i, row in enumerate(board):
for j in sorted(range(n), key=lambda j: (-row[j], j))[:3]:
cand.append((-row[j], i, j))
cand.sort()
cnt = [0] * n
top = []
for v, i, j in cand:
if cnt[j] < 3:
cnt[j] += 1
top.append((v, i, j))
top = top[:20]
ans = -(10**18)
k = len(top)
for a in range(k):
for b in range(a + 1, k):
if top[a][1] == top[b][1] or top[a][2] == top[b][2]:
continue
for c in range(b + 1, k):
if top[c][1] in (top[a][1], top[b][1]):
continue
if top[c][2] in (top[a][2], top[b][2]):
continue
ans = max(ans, -(top[a][0] + top[b][0] + top[c][0]))
return ans