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

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum

·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(一次通過)

解題思路
#

過程中的值是 start + prefix[i](Prefix Sum),全部都要 >= 1,最難滿足的是最小的前綴和:start >= 1 - min(prefix)。起始值本身也要是正數,所以再跟 1 取最大值。

我的解法
#

class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        cur = low = 0
        for x in nums:
            cur += x
            low = min(low, cur)
        return 1 - low

複雜度
#

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

要特別避免的錯誤
#

  • low 從 0 開始,等於把「起始值本身要 >= 1」也算進去了。

面試口說整理
#

每一步的值是起始值加上前綴和,我找出最小的前綴和,起始值就是 1 減掉它;最小值從 0 開始算,所以答案至少是 1。時間 O(n)。

相關文章

LeetCode 1480: Running Sum of 1d Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1480 解題筆記:前綴和的定義,每一格加上前一格
LeetCode 1732: Find the Highest Altitude
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1732 解題筆記:海拔就是 gain 的前綴和,起點是 0,取最大值
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 解題筆記:排序後跟原本的陣列逐一比較,數有幾個位置不同