LeetCode 题解工作台
构成特定和需要添加的最少元素
给你一个整数数组 nums ,和两个整数 limit 与 goal 。数组 nums 有一条重要属性: abs(nums[i]) 。 返回使数组元素总和等于 goal 所需要向数组中添加的 最少元素数量 ,添加元素 不应改变 数组中 abs(nums[i]) 这一属性。 注意,如果 x >= 0 ,…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们先计算数组元素总和 ,然后计算 与 的差值 。 那么需要添加的元素数量为 的绝对值除以 向上取整,即 $\lceil \frac{|d|}{limit} \rceil$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个整数数组 nums ,和两个整数 limit 与 goal 。数组 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 <= 1051 <= limit <= 106-limit <= nums[i] <= limit-109 <= goal <= 109
解题思路
方法一:贪心
我们先计算数组元素总和 ,然后计算 与 的差值 。
那么需要添加的元素数量为 的绝对值除以 向上取整,即 。
注意,本题中数组元素的数据范围为 ,元素个数最大为 ,总和 以及差值 可能会超过 位整数的表示范围,因此需要使用 位整数。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
d = abs(sum(nums) - goal)
return (d + limit - 1) // limit
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.