LeetCode daily check-in (4) 1413. Step by step sum to get the minimum value of positive numbers

2022.8.9 One question per day

1413. Stepwise summing to get the minimum value of a positive number

topic description

You are given an integer array nums. You can choose any positive startValue as the initial value.

You need to traverse the nums array from left to right, and add startValue to the values ​​in the nums array in turn.

Please choose the smallest positive number as startValue under the premise of ensuring that the cumulative sum is always greater than or equal to 1.

Example 1:

输入:nums = [-3,2,-3,4,2]
输出:5
解释:如果你选择 startValue = 4,在第三次累加时,和小于 1 。
                累加求和
                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:

输入:nums = [1,2]
输出:1
解释:最小的 startValue 需要是正数。

Example 3:

输入:nums = [1,-2,-3]
输出:5

hint

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

solution

The difficulty of signing in. . Calculate the prefix sum and save the minimum value ans. If the minimum value is less than or equal to 0, the answer is 1-ans, and if it is positive, the answer is 1.

the code

class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int len=nums.size(),ans=1,now=0;
        for(int i=0;i<len;i++)
        {
            now+=nums[i];
            ans=min(now,ans);
        }
        if(ans!=1)
        ans=1-ans;
        return ans;
    }
};

code idea

ans saves the minimum value, the initial default is 1, if the minimum value is less than or equal to 0 in the loop, update the value of ans.

Summarize

Too simple and nothing to sum it up.

Guess you like

Origin blog.csdn.net/qq_43824745/article/details/126264835