Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums, you start with an initial positive value startValue. In each iteration you add nums[i] to your current value. Find the minimum positive startValue such that the running sum never drops below 1.
The running sum at index i is startValue + sum(nums[0..i]). For this to never drop below 1, startValue must be at least 1 - minPrefix, where minPrefix is the minimum prefix sum. Since startValue must be positive, the answer is max(1, 1 - minPrefix).
This is solved by computing prefix sums of nums, tracking the minimum value encountered, then returning the required start value. Time O(n), Space O(1).
Edge cases include all positive nums (startValue = 1), empty array (return 1), and large negative values.
The running sum computation is a simple DP prefix sum. By tracking the minimum prefix value, we determine the required starting offset to keep all prefix sums above zero. This technique is used in financial projections and cumulative cost analysis.
The minimum prefix sum represents the greatest cumulative deficit encountered. By setting startValue to 1 minus this deficit, we guarantee the running sum never falls below 1. This is a direct application of the prefix sum DP pattern where we maintain a running total and track its extremum.
Example Input & Output
Min prefix = -4, start = 5.
Min prefix sum = -4, start = 1-(-4)=5.
Only -5, start = 1-(-5)=6.
Zeros, start = 1.
All positive, start = 1.
Algorithm Flow

Solution Approach
Compute prefix sums tracking the minimum sum. Answer = 1 - minSum.
Time O(n), Space O(1).
Best Answers
class Solution {
public int solution(int[] nums) {
int min = 0, sum = 0;
for (int n : nums) {
sum += n;
if (sum < min) min = sum;
}
return 1 - min;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
