#3256

Maximum Value Sum by Placing Three Rooks I

Hard
ArrayDynamic ProgrammingMatrixEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m^3 * n^3)
O(m^3)
Space
O(1)
O(m)
💡

Intuition

Time O(m^3)Space O(m)

Instead of checking all combinations, we can first find the top three values in each row and store them. Then, we can iterate through combinations of three rows and calculate the maximum sum using pre-stored values, significantly reducing the number of calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each row, find the top three values and their respective column indices.
  2. 2Step 2: Store these values in a list of tuples for easy access.
  3. 3Step 3: Iterate through all combinations of three rows and calculate the maximum sum using the stored values, ensuring no column indices overlap.
solution.py17 lines
1from itertools import combinations
2
3def maxRookSum(board):
4    m, n = len(board), len(board[0])
5    top_values = []
6    for row in board:
7        values = sorted([(val, col) for col, val in enumerate(row)], reverse=True)[:3]
8        top_values.append(values)
9    max_sum = float('-inf')
10    for rows in combinations(range(m), 3):
11        for i in range(3):
12            for j in range(3):
13                for k in range(3):
14                    if top_values[rows[0]][i][1] != top_values[rows[1]][j][1] and top_values[rows[0]][i][1] != top_values[rows[2]][k][1] and top_values[rows[1]][j][1] != top_values[rows[2]][k][1]:
15                        current_sum = top_values[rows[0]][i][0] + top_values[rows[1]][j][0] + top_values[rows[2]][k][0]
16                        max_sum = max(max_sum, current_sum)
17    return max_sum

Complexity note: This complexity is more efficient because we only calculate the top three values per row once, and then we only iterate through combinations of rows, significantly reducing the number of calculations.

  • 1Rooks cannot attack each other if they are in different rows and columns.
  • 2Finding the top values in each row reduces the number of combinations we need to check.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.