↓Skip to main content
  1. LeetCode/

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

·1 min· ·
LeetCode Easy Array Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-23

  • Submissions: Accepted (first try)

Approach
#

The running values are start + prefix[i] (Prefix Sum) and all must be >= 1; the binding one is the minimum prefix sum, so start >= 1 - min(prefix). The start value must itself be positive, hence the max with 1.

My Solution
#

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

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Starting low at 0 also encodes “the start value itself must be >= 1”.

Interview Explanation
#

Each step’s value is the start plus a prefix sum, so I find the minimum prefix sum and answer 1 minus it; starting the minimum at 0 keeps the answer at least 1. Time O(n).

Related

LeetCode 1480: Running Sum of 1d Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1480 note: the definition of a prefix sum, adding each element to the previous running total
LeetCode 1732: Find the Highest Altitude
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1732 note: the altitudes are prefix sums of gain starting from 0; take the maximum
LeetCode 1991: Find the Middle Index in Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1991 note: compute the total, maintain the left sum while scanning, and get the right sum as total - left - nums[i]
LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original