Problem Link

Description


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 <= 100
  • 3 <= n == board[i].length <= 100
  • -109 <= board[i][j] <= 109

Solution


Python3

class Solution:
    def maximumValueSum(self, board: List[List[int]]) -> int:
        rows, cols = len(board), len(board[0])
        top3 = []
 
        for i in range(rows):
            A = []
 
            for j in range(cols):
                A.append([board[i][j], j])
            
            A.sort(reverse = 1)
 
            top3.append(A[:3])
        
        @cache
        def go(index, col1, col2, k):
            if k == 0: return 0
 
            if index == rows: return -inf
 
            # skip
            res = go(index + 1, col1, col2, k)
 
            for c in range(len(top3[index])):
                v, j = top3[index][c]
 
                if k == 3:
                    res = max(res, v + go(index + 1, j, col2, k - 1))
                elif k == 2 and j != col1:
                    res = max(res, v + go(index + 1, col1, j, k - 1))
                elif k == 1 and j != col1 and j != col2:
                    res = max(res, v + go(index + 1, col1, col2, k - 1))
            
            return res
        
        return go(0, None, None, 3)