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

这道题说是从一个startValue开始,从左往右加数组里的数字,要保证每次加完这个值都不小于1。翻译过来就是,求这个数组的prefix sum最小的那个数,如果最小的就不小于1,那就return最小的startValue which is 1,如果最小的小于1,那就return (-sum) + 1

复制代码
class Solution {
    public int minStartValue(int[] nums) {
        int min = Integer.MAX_VALUE;
        int sum = 0;
        for (int num : nums) {
            sum += num;
            min = Math.min(min, sum);
        }
        return min >= 1 ? 1 : 1 - min;
    }
}
相关推荐
来一碗刘肉面3 小时前
栈的应用(表达式求值)
数据结构·算法
xiaowang1234shs3 小时前
怪兽轻断食技术深度测评:从断食计时引擎到AI识别算法的工程实践解析
数据库·人工智能·算法·macos·机器学习·p2p·visual studio
小果因子实验室4 小时前
量化研究--策略迁移算法1研究
算法
Web极客码4 小时前
如何用三段式确定性剪枝,为 LLM Agent 砍掉 35% 的 Token 成本?
服务器·人工智能·算法·机器学习
程序猿乐锅4 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
wabs6665 小时前
关于图论【广度优先搜索的理论基础】
算法·图论·宽度优先
孤魂2335 小时前
逻辑回归算法
算法·机器学习·逻辑回归
weixin_377634845 小时前
【多模型预测】 如何合理融合多个预测分值
算法·机器学习·概率论·预测·agent预测
无风听海5 小时前
Claude Agent Skills 的四种设计模式;从渐进式披露到最小权限
java·算法·设计模式
37.2℃9955 小时前
专业的Claude Design解决方案
前端·算法