LeetCode Problem Workspace

Minimum Elements to Add to Form a Given Sum

Compute the gap between current sum and goal, then greedily cover it with limit-sized additions to get the minimum count.

category

2

Topics

code_blocks

7

Code langs

hub

3

Related

Practice Focus

Medium · Greedy choice plus invariant validation

bolt

Answer-first summary

Compute the gap between current sum and goal, then greedily cover it with limit-sized additions to get the minimum count.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Greedy choice plus invariant validation

Try AiBox Copilotarrow_forward

The key move in Minimum Elements to Add to Form a Given Sum is to ignore which values to add at first and focus on the remaining difference after summing nums. Once that gap is known, each new element can fix at most limit in absolute value, so the minimum number of additions is the ceiling of abs(goal - sum(nums)) divided by limit. This works because any smaller element choice cannot reduce the gap faster.

Problem Statement

You are given an integer array nums, a positive integer limit, and a target sum goal. You may append any number of integers to nums as long as every added integer stays within the inclusive range from -limit to limit. The task is to return the minimum number of new elements required so that the final array sum becomes exactly goal.

This problem is not about searching combinations inside nums. The useful invariant is the current sum of nums versus goal: once you know the remaining difference, every added element can shrink that gap by at most limit. For example, with nums = [1,-1,1], limit = 3, goal = -4, the current sum is 1, so the gap is 5 toward the negative side, and two added values are enough because one value can cover at most 3 of that distance.

Examples

Example 1

Input: nums = [1,-1,1], limit = 3, goal = -4

Output: 2

You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.

Example 2

Input: nums = [1,-10,9,1], limit = 100, goal = 0

Output: 1

Example details omitted.

Constraints

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

Solution Approach

1. Reduce the problem to a remaining gap

First compute the sum of nums. The only thing that matters afterward is the absolute difference between that sum and goal. Whether the gap is positive or negative changes the sign of added elements, but it does not change how many are needed.

2. Apply the greedy choice with the largest legal contribution

Each appended number can contribute at most limit toward closing the gap because its absolute value cannot exceed limit. To minimize the count, greedily assume every new element contributes as much as possible in the needed direction. That turns the problem into covering a distance of abs(goal - sum(nums)) using jumps of size at most limit.

3. Use ceiling division to get the exact minimum

If diff = abs(goal - sum(nums)), then the answer is ceil(diff / limit). In integer arithmetic, compute it as (diff + limit - 1) / limit. This is the invariant validation step: after k additions, the maximum total correction is k * limit, so any answer smaller than the ceiling cannot possibly reach goal, while the ceiling is always achievable by using full-size values and one final smaller value if needed.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Summing the array takes O(n) time, where n is nums.length, and the greedy calculation after that is O(1). The space usage is O(1) because you only track the running sum, the remaining difference, and the final count.

What Interviewers Usually Probe

  • The interviewer keeps pointing back to the target sum instead of asking which exact numbers you would add.
  • They ask what changes if you imagine nums starts empty, which hints that only the remaining gap matters.
  • They focus on the bound abs(x) <= limit, signaling a greedy maximum-contribution argument rather than subset reasoning.

Common Pitfalls or Variants

Common pitfalls

  • Trying to build the added numbers one by one instead of directly dividing the remaining gap by limit.
  • Forgetting the absolute value on goal - sum(nums), which breaks cases where the array sum is already above the target.
  • Using floor division instead of ceiling division, which undercounts whenever the gap is not a multiple of limit.

Follow-up variants

  • Ask for the actual values to append, not just the minimum count; the same greedy idea works by filling with +/-limit and one remainder.
  • 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.
  • Ask whether exactly k additions can reach goal; this becomes a feasibility check using whether k * limit can cover the remaining gap.

FAQ

What is the main idea in Minimum Elements to Add to Form a Given Sum?

Compute the current array sum, find the absolute gap to goal, and divide that gap by limit with ceiling division. The greedy step is valid because each added element can fix at most limit, so using smaller magnitudes cannot reduce the number of additions.

Why does the greedy choice work in this problem?

The invariant is that after adding k elements, the most total correction you can make is k * limit in absolute value. That means any solution needs at least ceil(diff / limit) elements, and that bound is reachable by taking values in the needed direction with magnitude limit except possibly the last one.

Do I need to construct the elements I add?

No. The problem only asks for the minimum count. Once you know the remaining difference, the exact values are only a witness that the count is achievable, not something you need to enumerate in code.

What is the most common bug for this greedy choice plus invariant validation pattern?

The usual mistake is using integer division without rounding up. If diff is 5 and limit is 3, floor division gives 1, but one element can correct at most 3, so you actually need 2.

Why is this tagged Array and Greedy instead of math only?

You still need one pass over the array to compute the starting sum, and the interview-worthy part is recognizing the greedy trade-off created by the per-element limit. The math formula comes directly from that Array scan plus the greedy bound.

terminal

Solution

Solution 1: Greedy

First, we calculate the sum of the array elements $s$, and then calculate the difference $d$ between $s$ and $goal$.

1
2
3
4
class Solution:
    def minElements(self, nums: List[int], limit: int, goal: int) -> int:
        d = abs(sum(nums) - goal)
        return (d + limit - 1) // limit
Minimum Elements to Add to Form a Given Sum Solution: Greedy choice plus invariant validati… | LeetCode #1785 Medium