- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 64 lines of C++ from the credited upstream file 3256.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long maximumValueSum(vector<vector<int>>& board) {4 const int m = board.size();5 const int n = board[0].size();6 long ans = LONG_MIN;7 using T = tuple<long, int, int>;8 vector<vector<T>> rows(m); 9 vector<vector<T>> cols(n); 10 set<T> rowSet; 11 set<T> colSet; 12 set<T> topNine; 13 14 for (int i = 0; i < m; ++i)15 for (int j = 0; j < n; ++j) {16 rows[i].emplace_back(board[i][j], i, j);17 cols[j].emplace_back(board[i][j], i, j);18 }19 20 auto getTop3 = [](vector<T>& row) -> vector<T> {21 partial_sort(row.begin(),22 row.begin() + min(3, static_cast<int>(row.size())),23 row.end(), greater<>());24 row.resize(min(3, (int)row.size()));25 return row;26 };27 28 for (vector<T>& row : rows) {29 row = getTop3(row);30 rowSet.insert(row.begin(), row.end());31 }32 33 for (vector<T>& col : cols) {34 col = getTop3(col);35 colSet.insert(col.begin(), col.end());36 }37 38 set_intersection(rowSet.begin(), rowSet.end(), colSet.begin(), colSet.end(),39 inserter(topNine, topNine.begin()));40 41 42 43 if (topNine.size() > 9) {44 auto it = topNine.begin();45 advance(it, topNine.size() - 9);46 topNine.erase(topNine.begin(), it);47 }48 49 for (auto it1 = topNine.begin(); it1 != topNine.end(); ++it1)50 for (auto it2 = next(it1); it2 != topNine.end(); ++it2)51 for (auto it3 = next(it2); it3 != topNine.end(); ++it3) {52 const auto [val1, i1, j1] = *it1;53 const auto [val2, i2, j2] = *it2;54 const auto [val3, i3, j3] = *it3;55 if (i1 == i2 || i1 == i3 || i2 == i3 || 56 j1 == j2 || j1 == j3 || j2 == j3)57 continue;58 ans = max(ans, val1 + val2 + val3);59 }60 61 return ans;62 }63};64