#3257
Maximum Value Sum by Placing Three Rooks II
HardArrayDynamic ProgrammingMatrixEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all combinations, we can precompute the top three values in each row, allowing us to quickly evaluate potential rook placements without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: For each row, find the top three values and their respective column indices.
- 2Step 2: Use a nested loop to iterate through the top three values of three different rows, ensuring no two rooks are in the same column.
- 3Step 3: Calculate the sum of the selected values and keep track of the maximum sum.
solution.py14 lines
1def maxRookSum(board):
2 m, n = len(board), len(board[0])
3 top_three = []
4 for row in board:
5 top_three.append(sorted([(val, col) for col, val in enumerate(row)], reverse=True)[:3])
6 max_sum = float('-inf')
7 for i in range(m):
8 for j in range(3):
9 for k in range(i + 1, m):
10 for l in range(3):
11 if top_three[i][j][1] != top_three[k][l][1]:
12 current_sum = top_three[i][j][0] + top_three[k][l][0]
13 max_sum = max(max_sum, current_sum)
14 return max_sumℹ
Complexity note: The time complexity is O(n) because we only need to find the top three values in each row, and the nested loops are limited to three iterations each, making it efficient.
- 1Precomputing values reduces redundant calculations.
- 2Using combinations wisely can optimize the search.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.