↓快轉到主要內容
  1. LeetCode/

LeetCode 1732: Find the Highest Altitude

·1 分鐘· ·
LeetCode Easy Array Prefix-Sum
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-11-23

  • 提交紀錄:Accepted(一次通過)

解題思路
#

第 i 個點的海拔是 gain[0] + ... + gain[i - 1],也就是前綴和(Prefix Sum)。起點海拔 0 也要算進去,所以答案至少是 0。

我的解法
#

class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        best = cur = 0
        for g in gain:
            cur += g
            best = max(best, cur)
        return best

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 起點 0 也是一個海拔,全部都往下時答案是 0。

面試口說整理
#

海拔就是 gain 的前綴和,我一邊累加一邊記錄最大值,起點 0 也算。時間 O(n)、空間 O(1)。

相關文章

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1413 解題筆記:起始值加上每個前綴和都要 >= 1,所以起始值是 max(1, 1 - 最小前綴和)
LeetCode 1480: Running Sum of 1d Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1480 解題筆記:前綴和的定義,每一格加上前一格
LeetCode 1991: Find the Middle Index in Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1991 解題筆記:先算總和,掃描時維護左邊的和,右邊的和是 total - left - nums[i]
LeetCode 1337: The K Weakest Rows in a Matrix
·1 分鐘
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 解題筆記:每列的士兵都在前面,用二分找第一個 0 就是士兵數;照(士兵數, 列號)排序取前 k 個
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 1051: Height Checker
·1 分鐘
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 解題筆記:排序後跟原本的陣列逐一比較,數有幾個位置不同