LeetCode 题解工作台

逐步求和得到正数的最小值

给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。 你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。 请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。 示例 1: …

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

class Solution: def minStartValue(self, nums: List[int]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。

你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。

请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。

 

示例 1:

输入: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

示例 2:

输入:nums = [1,2]
输出:1
解释:最小的 startValue 需要是正数。

示例 3:

输入:nums = [1,-2,-3]
输出:5

 

提示:

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        s, t = 0, inf
        for num in nums:
            s += num
            t = min(t, s)
        return max(1, 1 - t)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Understanding of prefix sums and cumulative calculations is required.

  • question_mark

    The candidate should be able to relate the concept of array adjustments and prefix sum manipulation to real-world scenarios.

  • question_mark

    The candidate may need to demonstrate efficiency in solving this problem with respect to both time and space.

warning

常见陷阱

外企场景
  • error

    Forgetting to consider the negative values in the array, which can reduce the cumulative sum below 1.

  • error

    Confusing the minimum prefix sum with the overall cumulative sum, leading to incorrect start values.

  • error

    Not optimizing the approach to handle larger arrays efficiently, which may result in time limit exceed errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to allow negative start values and analyze how the solution adapts.

  • arrow_right_alt

    Introduce more complex arrays, such as those with very large or very small numbers, and observe performance changes.

  • arrow_right_alt

    Add constraints to the problem, like limiting the number of positive or negative values, to test the robustness of the solution.

help

常见问题

外企场景

逐步求和得到正数的最小值题解:前缀和 | LeetCode #1413 简单