sagelearnai

Minimum Value to Get Positive Step by Step Sum

Difficulty: Easy · Pattern: Prefix Sum · LeetCode #1413

Choose a positive integer startValue. Adding the elements of nums one by one to it, the running total must never drop below 1. Return the minimum such startValue.

Examples

text
[-3, 2, -3, 4, 2]  →  5
[1, 2]             →  1
[1, -2, -3]        →  5

Hints

  1. The total at each step is startValue + prefix sum.
  2. The tightest constraint comes from the minimum prefix sum.

Approach

We need startValue + minPrefix ≥ 1, where minPrefix is the smallest prefix sum (taking 0 into account, since startValue itself must be ≥ 1). So the answer is max(1, 1 − minPrefix).

Complexity

Time: O(n). Space: O(1).

Python solution
def minStartValue(nums):
    s = lo = 0
    for x in nums:
        s += x
        lo = min(lo, s)
    return 1 - lo
JavaScript solution
function minStartValue(nums) {
  let s = 0, lo = 0;
  for (const x of nums) { s += x; lo = Math.min(lo, s); }
  return 1 - lo;
}