classSolution { public: longlongmaximumValueSum(vector<vector<int>>& board){ // the pre, suf we need: // when we reach a specific line, we want to know the top 3 biggest // numbers in different colomn, so we need an array size of // board.size(), with 3 pairs vector<vector<pair<int, int>>> pre, suf; int m = board.size(), n = board[0].size(); suf.resize(m, vector<pair<int, int>>(3, make_pair(INT_MIN, -1))); vector<int> mx(3, INT_MIN), c(3, -1); for (int i = m - 1; i >= 0; i--) { update(mx, c, i, board); suf[i][0] = make_pair(mx[0], c[0]); suf[i][1] = make_pair(mx[1], c[1]); suf[i][2] = make_pair(mx[2], c[2]); } fill(mx.begin(), mx.end(), INT_MIN); fill(c.begin(), c.end(), -1); longlong res = LLONG_MIN; for (int i = 0; i < m - 1; i++) { if (i) { for (int j = 0; j < n; j++) { // now, iterate through the pre, suf for (int k = 0; k < 3; k++) { if (c[k] == j) { continue; } for (int l = 0; l < 3; l++) { if (suf[i + 1][l].second != j && suf[i + 1][l].second != c[k]) { longlong tmp = (longlong)suf[i + 1][l].first + board[i][j] + mx[k]; res = max(tmp, res); break; } } } } } update(mx, c, i, board); } return res; }
voidupdate(vector<int>& m, vector<int>& c, int i, vector<vector<int>>& board){ int n = board[0].size(); for (int j = 0; j < n; j++) { if (board[i][j] > m[0]) { if (j != c[0]) { if (j != c[1]) { m[2] = m[1]; c[2] = c[1]; } m[1] = m[0]; c[1] = c[0]; } // if j is equal to c[0], then we just need to update the m[0] // and c[0] m[0] = board[i][j]; c[0] = j; } elseif (board[i][j] > m[1] && j != c[0]) { if (j != c[1]) { m[2] = m[1]; c[2] = c[1]; } m[1] = board[i][j]; c[1] = j; } elseif (board[i][j] > m[2] && j != c[0] && j != c[1]) { m[2] = board[i][j]; c[2] = j; } } } };