Minimum Value to Get Positive Step by Step Sum - 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).

Return the minimum positive value of startValue such that the step by step sum is never less than 1.

Input & Output

Example 1 — Negative Values
$ Input: nums = [-3,2,-3,4,2]
Output: 5
💡 Note: Starting with 5: 5+(-3)=2, 2+2=4, 4+(-3)=1, 1+4=5, 5+2=7. All values stay >= 1.
Example 2 — All Positive
$ Input: nums = [1,2]
Output: 1
💡 Note: Starting with 1: 1+1=2, 2+2=4. All values stay >= 1, so minimum start value is 1.
Example 3 — Large Negative Start
$ Input: nums = [-10,1,1,1,1]
Output: 11
💡 Note: Starting with 11: 11+(-10)=1, 1+1=2, 2+1=3, 3+1=4, 4+1=5. All values stay >= 1. With startValue=10: 10+(-10)=0, which violates the constraint.

Constraints

  • 1 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Minimum Value to Get Positive Step by Step Sum INPUT Array nums: -3 2 -3 4 2 i=0 i=1 i=2 i=3 i=4 Prefix Sums: -3 -1 -4 0 2 Goal: Find startValue so running sum is always greater than or equal to 1 Minimum Prefix Sum: minSum = -4 ALGORITHM STEPS 1 Initialize minSum = 0, sum = 0 2 Iterate Array Calculate running sum 3 Track Minimum minSum = min(minSum, sum) 4 Compute Result startValue = 1 - minSum Running Calculation: sum = 0 + (-3) = -3 sum = -3 + 2 = -1 sum = -1 + (-3) = -4 sum = -4 + 4 = 0 sum = 0 + 2 = 2 min! FINAL RESULT Formula: startValue = 1 - minSum startValue = 1 - (-4) = 5 Output: 5 Verification: With startValue = 5: 5 + (-3) = 2 [OK] 2 + 2 = 4 [OK] 4 + (-3) = 1 [OK] 1 + 4 = 5 [OK] 5 + 2 = 7 [OK] [OK] [OK] [OK] [OK] [OK] Key Insight: The minimum prefix sum tells us how negative the running sum can get. To ensure the step-by-step sum is always at least 1, we need startValue = 1 - minPrefixSum. This is an O(n) optimal solution that only requires a single pass through the array to track the minimum cumulative sum. TutorialsPoint - Minimum Value to Get Positive Step by Step Sum | Optimal Solution O(n)
Asked in
Amazon 25 Microsoft 18 Google 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen