【Leetcode】python - [2274] Maximum Consecutive Floors Without Special Floors 個人解法筆記 | 293rd LeetCode Weekly Contest

題目出處

2274. Maximum Consecutive Floors Without Special Floors

難度

medium

個人範例程式碼

class Solution:
    def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:
        if bottom >= top:
            return 0

        special.sort()
        max_floor = max(top - special[-1], special[0] - bottom)
        for i, s in enumerate(special):
            if i > 0:
                max_floor = max(special[i] - special[i-1] - 1 , max_floor) 

        return max_floor

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

這題有點像是 interval 的變化版,
幸好題目幫我們把限制設定好 (bottom < special floors < top),
不然處理上會有更多細節要注意。

input handling

如果 bottom >= top,return 0 (錯誤的 case)

一開始先處理 top 跟 sorting 後的 special[-1],差了多少 (可能為 0),
以及 bottom 與 sorting 後的 special[0],差了多少 (可能為 0)。

這邊真的要幸好題目設定好這些限制,不然處理上真的會麻煩很多…

再來做中間層的處理。

Boundary conditions

for loop 控制範圍

Reference