[LeetCode] Maximum Value Sum by Placing Three Rooks I

3256. Maximum Value Sum by Placing Three Rooks I

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
long long maximumValueSum(vector<vector<int>>& A) {
long long n = A.size(), m = A[0].size();
vector<long long> dp1(m,-1e18), dp2(m,-1e18);
long long res = -1e18;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) res = max(res, A[i][j] + dp2[j]);
vector<array<long long, 3>> best;
for(int j = 0; j < m; j++) {
for(int k = 0; k < m; k++) {
if(j == k) continue;
best.push_back({dp1[j] + A[i][k], j, k});
}
}
sort(rbegin(best), rend(best));
for(int j = 0; j < m; j++) {
for(auto& [val, idx1, idx2] : best) {
if(j == idx1 or j == idx2) continue;
dp2[j] = max(dp2[j], val);
break;
}
}
for(int j = 0; j < m; j++) dp1[j] = max(dp1[j], 1ll * A[i][j]);
}
return res;
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/18/PS/LeetCode/maximum-value-sum-by-placing-three-rooks-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.