We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Value to Get Positive Step by Step Sum

Number: 1514

Difficulty: Easy

Paid? No

Companies: Goldman Sachs, Amazon, Meta, Swiggy


Problem Description

Given an array of integers nums, determine the minimum positive integer startValue such that when adding startValue to the elements of nums one by one (i.e., calculating the step by step prefix sum), the running total never falls below 1.


Key Insights

  • The problem requires monitoring the prefix sum as elements are added.
  • The running minimum prefix sum dictates how low the cumulative sum can go.
  • If the minimum prefix sum is below 1, then the startValue must compensate by at least (1 - minimum prefix sum).
  • A linear pass through the nums array using a running sum is sufficient.

Space and Time Complexity

Time Complexity: O(n) where n is the number of elements in nums, as there is one pass through the array. Space Complexity: O(1) as only a few extra variables are used.


Solution

The approach is to compute the cumulative sum while iterating over the nums array and keep track of the minimum prefix sum encountered. If this minimum sum is less than 1, it indicates the deficit that needs to be overcome by the initial value startValue, which is calculated as (1 - lowest prefix sum). This guarantees that the running sum will be at least 1 at all times. If the minimum prefix sum is greater than or equal to 1, the startValue remains 1 since no extra boost is needed. The solution uses a simple iteration (prefix sum technique) and constant extra space.


Code Solutions

def minStartValue(nums):
    # Initialize the cumulative sum and the minimum prefix sum
    cumulative_sum = 0
    min_prefix_sum = float('inf')
    
    # Iterate through each number in the array
    for num in nums:
        cumulative_sum += num    # Update cumulative sum
        min_prefix_sum = min(min_prefix_sum, cumulative_sum)  # Track the minimum prefix sum seen

    # If minimum prefix sum is below 1, calculate required additional startValue
    # Otherwise, return 1 as start value since we are already >= 1 at all points.
    return 1 if min_prefix_sum >= 1 else 1 - min_prefix_sum

# Example usage:
nums = [-3, 2, -3, 4, 2]
print(minStartValue(nums))  # Output: 5
← Back to All Questions