Minimum Value to Get Positive Step by Step Sum — LeetCode 1413 Python Solution

EasyArrayPrefix Sum
Problem
#1413
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

Example

Input
nums = [-3,2,-3,4,2]
Output
5
Explanation
If you choose startValue = 4, in the third iteration your step by step sum is less than 1.

Python solution

Python
class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        s, t = 0, inf
        for num in nums:
            s += num
            t = min(t, s)
        return max(1, 1 - t)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1413. Minimum Value to Get Positive Step by Step Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1413. Minimum Value to Get Positive Step by Step Sum?
LeetCode 1413. Minimum Value to Get Positive Step by Step Sum is rated Easy on LeetCode.
What is the time complexity of LeetCode 1413. Minimum Value to Get Positive Step by Step Sum?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1413. Minimum Value to Get Positive Step by Step Sum?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1413. Minimum Value to Get Positive Step by Step Sum cover?
LeetCode 1413. Minimum Value to Get Positive Step by Step Sum is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview