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;
    }
}
相关推荐
khalil102013 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
学习3人组13 小时前
柔性排产时序算法+中间过程+阶段目标 细化表格
算法·mes
he___H13 小时前
算法快与慢--哈希+双指针
算法·leetcode·哈希算法
呃呃本13 小时前
算法题(回溯)
算法
刀法如飞14 小时前
Rust数组去重的20种实现方式,AI时代用不同思路解决问题
人工智能·算法·ai编程
yxc_inspire14 小时前
25年CCPC福建邀请赛补题
学习·算法
Raink老师14 小时前
用100道题拿下你的算法面试(链表篇-4):合并 K 个有序链表
算法·链表·面试
Liangwei Lin14 小时前
LeetCode 20. 有效的括号
算法
richard_yuu15 小时前
数据结构|二叉树层序遍历 & 线索二叉树:吃透二叉树进阶核心考点
数据结构
IronMurphy15 小时前
【算法四十四】322. 零钱兑换
算法