Compute the Minimum Value to Get Positive Step by Step Sum using Prefix Sum Algorithm


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.

Example 1:
Input: nums = [-3,2,-3,4,2]

Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.

step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1  | (5 -3 ) = 2    |  -3
(1 +2 ) = 3  | (2 +2 ) = 4    |   2
(3 -3 ) = 0  | (4 -3 ) = 1    |  -3
(0 +4 ) = 4  | (1 +4 ) = 5    |   4
(4 +2 ) = 6  | (5 +2 ) = 7    |   2

Example 2:
Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive.

Example 3:
Input: nums = [1,-2,-3]
Output: 5

Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100

Hints:
Find the minimum prefix sum.

Prefix Sum Algorithm

We can compute the minimal prefix sum using O(N) loop. The final answer is -minSum + 1.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int sum = 0, minsum = 0;
        for (const auto &n: nums) {
            sum += n;
            minsum = min(minsum, sum);
        }
        return -minsum + 1;
    }
};
class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int sum = 0, minsum = 0;
        for (const auto &n: nums) {
            sum += n;
            minsum = min(minsum, sum);
        }
        return -minsum + 1;
    }
};

We can also use the std::accumulate to do this:

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int minsum = 0;
        std::accumulate(begin(nums), end(nums), 0, [&](auto &a, auto &b) {
            minsum = min(minsum, a + b);
            return a + b;
        });            
        return -minsum + 1;
    }
};
class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int minsum = 0;
        std::accumulate(begin(nums), end(nums), 0, [&](auto &a, auto &b) {
            minsum = min(minsum, a + b);
            return a + b;
        });            
        return -minsum + 1;
    }
};

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
323 words
Last Post: How to Construct Binary Search Tree from Preorder Traversal in Python?
Next Post: Depth First Search Algoritm to Compute The k-th Lexicographical String of All Happy Strings of Length n

The Permanent URL is: Compute the Minimum Value to Get Positive Step by Step Sum using Prefix Sum Algorithm

Leave a Reply