LeetCode 807. Max Increase to Keep City Skyline

题目链接:https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/

题目解析:O(n^{2})的做法,找到Column和Row中的最大值,然后sum加上当前位置横纵数值的min与当前高度之差即可。

有个小优化是,在循环里面同时找出横纵的最大值,可以减少数组读取。

代码如下:0ms Accepted

class Solution {
public:
    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
        int maxColumn = grid.size(), maxRow = grid[0].size();
        int maxInColumn[maxColumn] = {0}, maxInRow[maxRow] = {0};
        for (int i = 0; i < maxColumn; i++)
        {
            int max = 0, max1 = 0;
            for (int j = 0; j < maxRow; j++)
            {
                if (grid[i][j] > max)
                    max = grid[i][j];
                if (grid[j][i] > max1)
                    max1 = grid[j][i];
            }
            maxInColumn[i] = max;
            maxInRow[i] = max1;
        }
        int sum = 0;
        for (int i = 0; i < maxColumn; i++)
            for (int j = 0; j < maxRow; j++)
                sum += min(maxInColumn[i], maxInRow[j]) - grid[i][j];
        return sum;
    }
};

static const auto ____ = [] () {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

猜你喜欢

转载自blog.csdn.net/github_36324732/article/details/81192920