Minimum Value to Get Positive Step by Step Sum

easy array prefix sum

Problem

Given an array nums, choose a positive integer startValue such that the running sum startValue + nums[0] + nums[1] + … is never less than 1 at any step. Return the minimum such startValue.

Inputnums = [-3, 2, -3, 4, 2]
Output5
Minimum prefix is -4 at index 2; startValue = 1 − (−4) = 5 keeps every prefix ≥ 1.

def min_start_value(nums):
    s = 0
    mn = 0
    for x in nums:
        s += x
        if s < mn:
            mn = s
    return 1 - mn
function minStartValue(nums) {
  let s = 0, mn = 0;
  for (const x of nums) {
    s += x;
    if (s < mn) mn = s;
  }
  return 1 - mn;
}
class Solution {
    public int minStartValue(int[] nums) {
        int s = 0, mn = 0;
        for (int x : nums) {
            s += x;
            if (s < mn) mn = s;
        }
        return 1 - mn;
    }
}
int minStartValue(vector<int>& nums) {
    int s = 0, mn = 0;
    for (int x : nums) {
        s += x;
        if (s < mn) mn = s;
    }
    return 1 - mn;
}
Time: O(n) Space: O(1)