You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.
Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.
Note that abs(x) equals x if x >= 0, and -x otherwise.
Example 1:
Input: nums = [1,-1,1], limit = 3, goal = -4 Output: 2 Explanation: 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
Constraints:
1 <= nums.length <= 1051 <= limit <= 106-limit <= nums[i] <= limit-109 <= goal <= 109Problem Overview: You are given an integer array nums, a maximum allowed absolute value limit, and a target goal. You can append numbers between -limit and limit. The task is to compute the minimum number of elements required so the final array sum becomes exactly goal.
Approach 1: Simple Calculation Using Greedy Strategy (Time: O(n), Space: O(1))
First compute the current sum of the array using a single pass. The difference between the target and current sum is diff = |goal - sum(nums)|. Each number you add can contribute at most limit toward reducing this difference because its absolute value cannot exceed limit. The optimal strategy is greedy: always use the maximum allowed magnitude to close the gap as quickly as possible. The number of elements required is therefore ceil(diff / limit). This works because using smaller values would only increase the count of elements needed. The algorithm only scans the array once to compute the sum and then performs constant-time math.
This method relies on a greedy observation rather than exploring combinations. Since each inserted element contributes independently to reducing the remaining difference, maximizing each contribution minimizes the number of operations. The approach fits naturally into problems tagged with Greedy and basic Array processing.
Approach 2: Binary Search on Number of Added Elements (Time: O(n + log(diff)), Space: O(1))
Instead of computing the answer directly, you can frame the problem as searching for the smallest k such that k * limit ≥ diff. Start by calculating the same difference diff = |goal - sum(nums)|. Then perform Binary Search over the possible number of added elements. For a candidate value k, check if the maximum achievable adjustment (k * limit) is sufficient to cover diff. If it is, try smaller values; otherwise increase k. This approach is more algorithmic but ultimately arrives at the same answer as the greedy formula.
The binary search formulation can help when reasoning about feasibility conditions or when constraints become more complex in follow‑up problems. However, the mathematical greedy calculation is simpler and faster in practice.
Recommended for interviews: The greedy calculation is the expected solution. Interviewers typically want to see the observation that each added number can reduce the difference by at most limit, which immediately leads to ceil(diff / limit). Explaining the reasoning clearly demonstrates stronger problem‑solving skills than implementing a heavier search approach.
First, calculate the sum of the existing nums array. The target sum needed is given by the goal. To determine how much more (or less) we need to add, find the absolute difference between the current sum and the goal value. The key insight here is that to reduce the number of new elements required, each added element should be as large as possible, constrained by the limit parameter. Therefore, the minimum number of elements we need is the ceiling of the division of the absolute difference by limit.
The solution first calculates the sum of the array, determines the difference to the goal, and computes the minimum number of elements needed using integer division. This is implemented using the formula (diff + limit - 1) / limit to perform ceiling division.
Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(1), as no extra space is used apart from variables.
Use a binary search to find the minimum number of elements needed. First compute the difference between the current sum and the goal. Using binary search, check if it is possible to reach the goal by adding a certain number of elements, considering their limits. This approach is not more efficient than the greedy method above but offers a different perspective to the problem.
This C implementation uses binary search to identify the minimum number of elements required to adjust the array sum to match goal. It tests potential solutions by checking if multiplying potential counts by limit covers the required diff.
Time Complexity: O(n + log(diff / limit)), where n is the length of nums.
Space Complexity: O(1).
First, we calculate the sum of the array elements s, and then calculate the difference d between s and goal.
The number of elements to be added is the absolute value of d divided by limit and rounded up, that is, \lceil \frac{|d|}{limit} \rceil.
Note that in this problem, the data range of array elements is [-10^6, 10^6], the maximum number of elements is 10^5, the total sum s and the difference d may exceed the range of 32-bit integers, so we need to use 64-bit integers.
The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the array nums.
| Approach | Complexity |
|---|---|
| Simple Calculation Using Greedy Strategy | Time Complexity: O(n), where n is the number of elements in |
| Binary Search Approach | Time Complexity: O(n + log(diff / limit)), where n is the length of |
| Greedy | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Calculation | O(n) | O(1) | Best general solution. Direct mathematical insight using ceil(diff/limit). |
| Binary Search on Answer | O(n + log(diff)) | O(1) | Useful when modeling the problem as a feasibility check or extending to more complex constraints. |
Minimum Elements to Add to Form a Given Sum | leetcode 1785 • Coding Decoded • 767 views views
Watch 5 more video solutions →Practice Minimum Elements to Add to Form a Given Sum with our built-in code editor and test cases.
Practice on FleetCode