807. 保持城市天际线

class Solution {
public:
    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
        int n=grid.size();
        vector<int>rowMaxHeights(n,0);
        vector<int>colMaxHeights(n,0);
        //保存每一行的最高值
        for(int i=0;i<n;++i)
            rowMaxHeights[i]= *max_element(grid[i].begin(),grid[i].end());
        //保存每一列的最高值
        for(int i=0;i<n;++i){
            for(int j=0;j<n;++j){
                colMaxHeights[i] = max(colMaxHeights[i],grid[j][i]);
            }
        }
        int res=0;
        for(int i=0;i<n;++i){
            for(int j=0;j<n;++j){
                int maxHeight = min(rowMaxHeights[i],colMaxHeights[j]);
                grid[i][j]=maxHeight;
                res+=max(0,maxHeight-grid[i][j]);
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode,算法,java,数据结构)