Keshawn_lu's Blog

Leetcode 1413. 逐步求和得到正数的最小值

字数统计: 279阅读时长: 1 min
2022/08/09 Share

题目简介:

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

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

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

示例 1:

1
2
3
4
5
6
7
8
9
10
输入: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

示例 2:

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

思路:

依次遍历数组,将元素值依次相加,找到一个元素值最小的前缀和,此时所需的startValue便是答案。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minStartValue(vector<int>& nums) {

int res = 1;

int count = 0;
for(int i = 0; i < nums.size(); ++i){

count += nums[i];

if(count < 1){

res = max(res, 1 - count);
}
}

return res;

}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: