当前位置:网站首页>力扣 1413. 逐步求和得到正数的最小值
力扣 1413. 逐步求和得到正数的最小值
2022-08-09 21:54:00 【冷酷的摸鱼小将】
题目
给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。
你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。
请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。
示例
输入: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
输入:nums = [1,2]
输出:1
解释:最小的 startValue 需要是正数。
输入:nums = [1,-2,-3]
输出:5
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-value-to-get-positive-step-by-step-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:模拟
Java实现
class Solution {
public int minStartValue(int[] nums) {
int res = 0, n = nums.length;
int flag = -1;
while (flag == -1) {
res++;
int i = 0, sum = res;
for (i = 0; i < n; i++) {
sum += nums[i];
if (sum < 1) break;
}
if (i == n) flag = 1;
}
return res;
}
}

方法2:贪心

Java实现
class Solution {
public int minStartValue(int[] nums) {
int sum = 0, sumMin = 0;
for (int num : nums) {
sum += num;
sumMin = Math.min(sum, sumMin);
}
return 1 - sumMin;
}
}

边栏推荐
- Deceptive Dice
- 每日一R「02」所有权与 Move 语义
- 一本通2074:【21CSPJ普及组】分糖果(candy)
- Interpretation of the paper (DropEdge) "DropEdge: Towards Deep Graph Convolutional Networks on Node Classification"
- 2022 首期线下 Workshop!面向应用开发者们的数据应用体验日来了 | TiDB Workshop Day
- Technology Sharing | How to use the JSON Schema mode of interface automation testing?
- Leetcode 93 复原IP地址
- String hashing (2014 SERC J question)
- SecureCRT sets the timeout period for automatic disconnection
- 【微服务~Nacos】Nacos之配置中心
猜你喜欢
随机推荐
一文让你快速了解隐式类型转换【整型提升】!
TF中使用zeros(),ones(), fill()方法生成数据
论文解读(DropEdge)《DropEdge: Towards Deep Graph Convolutional Networks on Node Classification》
小程序+自定义插件的关键性
CVPR22 Oral|通过多尺度token聚合分流自注意力,代码已开源
JS Deobfuscation - AST Restoration Case
Jinshanyun earthquake, the epicenter is in bytes?
6 rules to sanitize your code
STC8H development (15): GPIO drive Ci24R1 wireless module
4D Summary: 38 Knowledge Points of Distributed Systems
np中的round函数,ceil函数与floor函数
重要的不是成为海贼王,而是像路飞一样去冒险
Converting angles to radians
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Technology Sharing | How to use the JSON Schema mode of interface automation testing?
从产品角度看 L2 应用:为什么说这是一个游乐场?
OKR 锦囊妙计
Leetcode 93 IP addresses
2.1.5 大纲显示问题
ACM MM 2022 | Cloud2Sketch: Painting with clouds in the sky, AI brush strokes







