LeetCode 题解工作台

构成特定和需要添加的最少元素

给你一个整数数组 nums ,和两个整数 limit 与 goal 。数组 nums 有一条重要属性: abs(nums[i]) 。 返回使数组元素总和等于 goal 所需要向数组中添加的 最少元素数量 ,添加元素 不应改变 数组中 abs(nums[i]) 这一属性。 注意,如果 x >= 0 ,…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们先计算数组元素总和 ,然后计算 与 的差值 。 那么需要添加的元素数量为 的绝对值除以 向上取整,即 $\lceil \frac{|d|}{limit} \rceil$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,和两个整数 limitgoal 。数组 nums 有一条重要属性:abs(nums[i]) <= limit

返回使数组元素总和等于 goal 所需要向数组中添加的 最少元素数量 ,添加元素 不应改变 数组中 abs(nums[i]) <= limit 这一属性。

注意,如果 x >= 0 ,那么 abs(x) 等于 x ;否则,等于 -x

 

示例 1:

输入:nums = [1,-1,1], limit = 3, goal = -4
输出:2
解释:可以将 -2 和 -3 添加到数组中,数组的元素总和变为 1 - 1 + 1 - 2 - 3 = -4 。

示例 2:

输入:nums = [1,-10,9,1], limit = 100, goal = 0
输出:1

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= limit <= 106
  • -limit <= nums[i] <= limit
  • -109 <= goal <= 109
lightbulb

解题思路

方法一:贪心

我们先计算数组元素总和 ss,然后计算 ssgoalgoal 的差值 dd

那么需要添加的元素数量为 dd 的绝对值除以 limitlimit 向上取整,即 dlimit\lceil \frac{|d|}{limit} \rceil

注意,本题中数组元素的数据范围为 [106,106][-10^6, 10^6],元素个数最大为 10510^5,总和 ss 以及差值 dd 可能会超过 3232 位整数的表示范围,因此需要使用 6464 位整数。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
class Solution:
    def minElements(self, nums: List[int], limit: int, goal: int) -> int:
        d = abs(sum(nums) - goal)
        return (d + limit - 1) // limit
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The interviewer keeps pointing back to the target sum instead of asking which exact numbers you would add.

  • question_mark

    They ask what changes if you imagine nums starts empty, which hints that only the remaining gap matters.

  • question_mark

    They focus on the bound abs(x) <= limit, signaling a greedy maximum-contribution argument rather than subset reasoning.

warning

常见陷阱

外企场景
  • error

    Trying to build the added numbers one by one instead of directly dividing the remaining gap by limit.

  • error

    Forgetting the absolute value on goal - sum(nums), which breaks cases where the array sum is already above the target.

  • error

    Using floor division instead of ceiling division, which undercounts whenever the gap is not a multiple of limit.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Ask for the actual values to append, not just the minimum count; the same greedy idea works by filling with +/-limit and one remainder.

  • arrow_right_alt

    Change the bound so each added element comes from a custom allowed set; then the simple ceiling formula may fail and the greedy proof must be revisited.

  • arrow_right_alt

    Ask whether exactly k additions can reach goal; this becomes a feasibility check using whether k * limit can cover the remaining gap.

help

常见问题

外企场景

构成特定和需要添加的最少元素题解:贪心·invariant | LeetCode #1785 中等