当前位置:网站首页>力扣 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;
}
}
边栏推荐
- LeetCode26: remove duplicates in sorted array
- Let's talk about what DDL, DML, DQL and DCL are in SQL statements
- STC8H开发(十五): GPIO驱动Ci24R1无线模块
- 重要的不是成为海贼王,而是像路飞一样去冒险
- 【GORM】模型关系-HasMany关系
- laravel table migration error [easy to understand]
- SQLi-LABS Page-2 (Adv Injections)
- Basic operations of openGauss database (super detailed)
- 电脑系统重装后怎么用打印机扫描出文件?
- 2.1.5 大纲显示问题
猜你喜欢
Bean life cycle
每日一R「02」所有权与 Move 语义
Flask之路由(app.route)详解
一本通2074:【21CSPJ普及组】分糖果(candy)
Shanghai Konan SmartRocket series product introduction (3): SmartRocket iVerifier computer interlocking system verification tool
JSON 基本使用
肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
简单问题窥见数学
国内手机厂商曾为它大打出手,如今它却最先垮台……
This article lets you quickly understand implicit type conversion [integral promotion]!
随机推荐
台风生成,广州公交站场积极开展台风防御安全隐患排查
nvm下node安装;node环境变量配置
String hashing (2014 SERC J question)
Basic JSON usage
STC8H Development (15): GPIO Drives Ci24R1 Wireless Module
大型分布式存储方案MinIO介绍,看完你就懂了!
Use zeros(), ones(), fill() methods to generate data in TF
np中的round函数,ceil函数与floor函数
一文让你快速了解隐式类型转换【整型提升】!
SecureCRT sets the timeout period for automatic disconnection
肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
TF中使用zeros(),ones(), fill()方法生成数据
【微服务~Nacos】Nacos服务提供者和服务消费者
leetcode 刷题日记 计算右侧小于当前元素的个数
json case
论文解读(DropEdge)《DropEdge: Towards Deep Graph Convolutional Networks on Node Classification》
STC8H development (15): GPIO drive Ci24R1 wireless module
Bean life cycle
Tensorflow中使用convert_to_tensor去指定数据的类型
unit test