Leetcode 2943. Maximize Area of Square Hole in Grid

  • Leetcode 2943. Maximize Area of Square Hole in Grid
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:2943. Maximize Area of Square Hole in Grid

1. 解题思路

这一题的话其实横轴和竖轴可以分开来独立考察,因为两者互不影响,我们最终的答案一定是两者之中能够构成的最大连续空格之中的较小值的平方。

因此,我们只需要用贪婪算法分别考察横轴上和纵轴上能够获取的最大连续空洞即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def maximizeSquareHoleArea(self, n: int, m: int, hBars: List[int], vBars: List[int]) -> int:
        hBars = sorted(hBars)
        vBars = sorted(vBars)
        
        def get_max_block(bars):
            lb, nxt = 1, 2
            ans = 1
            for loc in bars:
                if loc == nxt:
                    nxt = loc + 1
                else:
                    ans = max(ans, nxt - lb)
                    lb, nxt = loc-1, loc+1
            ans = max(ans, nxt - lb)
            return ans
        
        h_max = get_max_block(hBars)
        v_max = get_max_block(vBars)
        ans = min(h_max, v_max)
        return ans * ans

提交代码评测得到:耗时51ms,占用内存16.4MB。

你可能感兴趣的:(leetcode笔记,leetcode,2943,leetcode,medium,leetcode,双周赛118,leetcode,题解)