[LeetCode] 1413. Minimum Value to Get Positive Step by Step Sum

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

逐步求和得到正数的最小值。

给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。

你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。

请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-value-to-get-positive-step-by-step-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是请你找到一个 startValue ,然后与nums里面的每一个数字相加,使得过程中保证累加和在任何时候都大于等于1。

思路是先计算 nums 的前缀和,在过程中记录一个全局的最小值 min。如果这个 min 值大于1,则 startValue = 1 即可;但是如果这个 min 值小于1,startValue 需要保证起码是 Math.abs(min) + 1,这样就能确保在过程中,前缀和一直满足题意。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int minStartValue(int[] nums) {
 3         int sum = 0;
 4         int min = 0;
 5         for (int num : nums) {
 6             sum += num;
 7             min = Math.min(min, sum);
 8         }
 9         
10         if (min > 0) {
11             return 1;
12         } else {
13             return Math.abs(min) + 1;
14         }
15     }
16 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14176531.html