当前位置:网站首页>力扣 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;
}
}

边栏推荐
- 每日一R「02」所有权与 Move 语义
- 【EF】数据表全部字段更新与部分字段更新
- navicat 快捷键
- Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
- BulkInsert方法实现批量导入
- 阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
- 面试官:Redis 大 key 要如何处理?
- 在“企业通讯录”的盲区,融云的边界与分寸
- Tensorflow中placeholder函数的用法
- 【微服务~Nacos】Nacos之配置中心
猜你喜欢

Bean life cycle

2022 首期线下 Workshop!面向应用开发者们的数据应用体验日来了 | TiDB Workshop Day

Simple questions peek into mathematics

Flask入门学习教程

Space not freed after TRUNCATE table

从源码方面来分析Fragment管理中 Add() 方法

小程序+自定义插件的关键性

你真的了解乐观锁和悲观锁吗?

Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!

APP自动化测试框架-UiAutomator2基础入门
随机推荐
简单问题窥见数学
一本通2074:【21CSPJ普及组】分糖果(candy)
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
Evolution of MLOps
Activiti7审批流
TF生成均匀分布的tensor
2.1.5 大纲显示问题
论文解读(DropEdge)《DropEdge: Towards Deep Graph Convolutional Networks on Node Classification》
【EF】数据表全部字段更新与部分字段更新
OpenMLDB + Jupyter Notebook:快速搭建机器学习应用
STC8H开发(十五): GPIO驱动Ci24R1无线模块
Js fifteen interview questions (with answers)
开发者必备:一文快速熟记【数据库系统】和【软件开发模型】常用知识点
MLOps的演进历程
[Cloud Native] 4.2 DevOps Lectures
Flask之路由(app.route)详解
Five Star Holdings Wang Jianguo: Deepen the track with "plant spirit" and promote growth with "animal spirit"
FileZilla搭建FTP服务器图解教程
Xiaohei leetcode's refreshing rainy day trip, just finished eating Yufei Beef Noodles, Mala Tang and Beer: 112. Path Sum
第十七期八股文巴拉巴拉说(数据库篇)