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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code