不是很难的题,O(n^2)解决。
主要的思路是确定你需要的信息,和状态转移方程。我们需要确定各个行列最大的高度:row[i], column[j],然后取 min(row[i], column[j]) - grid[i][j] 之和就可以了。
class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int total = 0; int maxX = 0, maxY = 0; vector<int> row, column; for (int i=0; i<grid.size(); ++i) { maxX = 0; maxY = 0; for (int j=0; j<grid[i].size(); ++j) { if (maxX < grid[i][j]) maxX = grid[i][j]; if (maxY < grid[j][i]) maxY = grid[j][i]; } row.push_back(maxX); column.push_back(maxY); } for (int i=0; i<grid.size(); ++i) { for (int j=0; j<grid[i].size(); ++j) { total += min(row[i], column[j]) - grid[i][j]; } } return total; } };