Minimum Elements to Add to Form a Given Sum - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,-1,1], limit = 3, goal = -4
Output: 2
💡 Note: Current sum is 1-1+1 = 1. Need to reach -4, so gap is 5. Using elements of size ≤3, we need at least ceil(5/3) = 2 elements, like adding [-3, -2].
Example 2 — Already at Goal
$ Input: nums = [1,-10,9,1], limit = 100, goal = 1
Output: 0
💡 Note: Current sum is 1-10+9+1 = 1, which equals the goal. No elements need to be added.
Example 3 — Large Gap
$ Input: nums = [1,2], limit = 2, goal = 10
Output: 4
💡 Note: Current sum is 3, goal is 10, gap is 7. Using max elements of size 2, we need ceil(7/2) = 4 elements.

Constraints

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

Visualization

Tap to expand
Minimum Elements to Add to Form a Given Sum INPUT nums array: 1 -1 1 [0] [1] [2] Current Sum = 1 + (-1) + 1 = 1 limit = 3 goal = -4 Constraint: |nums[i]| <= limit Added elements: |x| <= 3 ALGORITHM STEPS 1 Calculate Difference diff = |goal - sum| diff = |-4 - 1| = 5 2 Use Maximum Value Each element can be at most +/- limit = 3 3 Divide and Ceil count = ceil(diff / limit) count = ceil(5 / 3) = 2 4 Verify Solution Add -3 and -2: 1 + (-3) + (-2) = -4 Formula: result = (diff + limit - 1) / limit = (5 + 3 - 1) / 3 = 2 FINAL RESULT Modified Array: 1 -1 1 -3 -2 ADDED New Sum: 1 + (-1) + 1 + (-3) + (-2) = -4 OUTPUT 2 OK - Goal Reached! Sum = -4 = goal |-3| <= 3, |-2| <= 3 All constraints satisfied Key Insight: The greedy approach works because we want to minimize the number of elements added. To do this, we should always use the maximum possible value (limit) for each element. The answer is simply ceiling(|goal - currentSum| / limit), which gives the minimum elements needed to bridge the gap. TutorialsPoint - Minimum Elements to Add to Form a Given Sum | Greedy Mathematical Approach
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 5
18.5K Views
Medium Frequency
~15 min Avg. Time
654 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen