1785. Minimum Elements to Add to Form a Given Sum
https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/
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:
Example 2:
Constraints:
1 <= nums.length <= 105
1 <= limit <= 106
-limit <= nums[i] <= limit
-109 <= goal <= 109
数组nums满足abs(nums[i]) <= limit,问最少引入多少新元素能让sum(nums) == goal,要求nums性质不变。算出sum和goal的差并化为正数,再除元素上限limit即所需最少个数。
Last updated
Was this helpful?