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 togoal. The array must maintain its property that abs(nums[i]) <= limit.
Note that abs(x) equals x if x >= 0, and -x otherwise.
To reach the goal sum, we can add elements with the maximum allowed absolute value (limit) in the direction needed (positive or negative). The minimum number of elements is the ceiling of the absolute difference between the current sum and the goal divided by limit.
classSolution {
publicintminElements(int[] nums, int limit, int goal) {
long s = 0;
for (int x : nums) s += x;
long diff = Math.abs(goal - s);
return (int)((diff + limit - 1) / limit);
}
}
1
2
3
4
5
6
7
8
classSolution {
funminElements(nums: IntArray, limit: Int, goal: Int): Int {
var s = 0Lfor (x in nums) s += x
val diff = kotlin.math.abs(goal - s)
return ((diff + limit - 1) / limit).toInt()
}
}