Minimum Value to Get Positive Step by Step Sum

Given an array of integers nums, you start with an initial positive value start value.

In each iteration, you calculate the step-by-step sum of start value plus elements in nums (from left to right).

Return the minimum positive value of start value 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. 

Approach

Java

public class MinimumValue {
    public static void main(String[] args) {

        int[] nums = { -32, -342 };

        System.out.println(minStartValue(nums));

    }

    static int minStartValue(int[] nums) {

        int res = 1;
        int min1 = nums[0];

        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1];

            if (nums[i] < min1)
                min1 = nums[i];
        }
        if (min1 <= 0)
            res = Math.abs(min1) + 1;
        return res;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int minStartValue(vector<int&nums)
{

    int res = 1;
    int min1 = nums[0];

    for (int i = 1i < nums.size(); i++)
    {
        nums[i] += nums[i - 1];

        if (nums[i] < min1)
            min1 = nums[i];
    }
    if (min1 <= 0)
        res = abs(min1) + 1;
    return res;
}

int main()
{
    vector<intnums = {-32, -342};

    cout << minStartValue(nums<< "\n";

    return 0;
}


No comments:

Post a Comment