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;
    }
}
相关推荐
加农炮手Jinx4 分钟前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
借雨醉东风8 分钟前
程序分享--常见算法/编程面试题:旋转矩阵
c++·线性代数·算法·面试·职场和发展·矩阵
_深海凉_13 分钟前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
jghhh011 小时前
使用 MATLAB 实现支持向量回归 (SVR) 预测未来数据
算法·matlab
云泽8081 小时前
笔试算法 - 双指针篇(二):四大经典求和题型 + 有效三角形计数问题
c++·算法
qeen872 小时前
【数据结构】树的基本概念及存储
c语言·数据结构·c++·学习·
一江寒逸2 小时前
数据结构与算法之美:串(字符串)——从基础操作到KMP模式匹配,吃透面试最高频的字符串考点
数据结构·面试·职场和发展
刀法如飞3 小时前
【合并已排序数组的三种实现策略,哪一种更可取?】
算法·程序员
王老师青少年编程3 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【区间贪心】:种树
c++·算法·贪心·csp·信奥赛·区间贪心·种树
hi_ro_a3 小时前
C++ 哈希表封装 unordered_map /unordered_set
数据结构·c++·算法·哈希算法