#1413

Minimum Value to Get Positive Step by Step Sum

Easy
ArrayPrefix SumPrefix SumCumulative Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution focuses on calculating the minimum prefix sum of the cumulative sums of nums. This allows us to determine the minimum startValue directly by ensuring the cumulative sum never drops below 1.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable total to 0 and minPrefixSum to 0.
  2. 2Step 2: Iterate through each number in nums, updating total by adding the current number.
  3. 3Step 3: Update minPrefixSum to be the minimum of itself and total.
  4. 4Step 4: If minPrefixSum is less than 1, return 1 - minPrefixSum as the required startValue; otherwise, return 1.
solution.py7 lines
1def minStartValue(nums):
2    total = 0
3    minPrefixSum = 0
4    for num in nums:
5        total += num
6        minPrefixSum = min(minPrefixSum, total)
7    return 1 - minPrefixSum if minPrefixSum < 1 else 1

Complexity note: This solution runs in O(n) time because we only traverse the array nums once, and it uses O(1) space since we only maintain a few integer variables.

  • 1The minimum startValue is determined by the lowest point reached in the cumulative sum.
  • 2If the cumulative sum is always above 1, the minimum startValue is simply 1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.