Minimum Value to Get Positive Step by Step Sum

Easy

Topics
ArrayPrefix Sum

Given an array nums, pick a positive start value. The step-by-step total (start plus a running prefix of nums) must never drop below 1. Return the minimum positive start value.

Example 1

-3021-324324
Input:  nums = [-3,2,-3,4,2]
Output: 5

Example 2

1021
Input:  nums = [1,2]
Output: 1

Example 3

10-21-32
Input:  nums = [1,-2,-3]
Output: 5

Constraints

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Starting from some value x, the running total after i steps is x + prefix[i]. Every one of those must stay at least 1, so x has to satisfy x + prefix[i] >= 1 for every i — and the binding constraint is the smallest prefix sum.

So find the minimum prefix sum m and return 1 - m. One pass, no search needed.

The detail worth getting right: initialise the minimum to 0, not to the first prefix. If every prefix is positive, the tightest constraint is the empty prefix, and the answer is 1 — the smallest allowed starting value.

Approach

  1. Sweep, maintaining the running total and the minimum total seen, starting at 0.
  2. Return 1 - minimum.

Dry Run

nums = [-3,2,-3,4,2]

running   0  -3  -1  -4   0   2
minimum   0  -3  -3  -4  -4  -4

answer 1 - (-4) = 5

check with x = 5:  5, 2, 4, 1, 5, 7   all >= 1,
and x = 4 gives 4, 1, 3, 0, ... which fails at 0  ✓

nums = [1,2]
running  0 1 3 ; minimum stays 0 -> answer 1

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two accumulators. Materialising the prefix array first is O(n) for no benefit.

Common Pitfalls

  • Initialising the minimum to nums[0] or to the first prefix. When all prefixes are positive the answer must be 1, and seeding from the data gives something larger.
  • Returning -minimum or 1 + minimum. The requirement is >= 1, so the offset is 1 - minimum.
  • Binary searching the start value. Monotonic, so it works, but it is O(n log n) for something one pass settles.
  • Requiring the total to stay positive only at the end rather than at every step.

Full Solution — all languages

class Solution:
    def minStartValue(self, nums):
        total = 0
        mn = 0
        for x in nums:
            total += x
            mn = min(mn, total)
        return 1 - mn
Asked at Swiggy
SensAI
Beta
Tap the mic to stop voice mode