[LeetCode] Minimum Elements to Add to Form a Given Sum

1785. 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.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int minElements(vector<int>& nums, int limit, int goal) {
long long sum = 0;
for(auto& num : nums)
sum += num;
int cnt = abs(sum - goal) / limit + (abs(sum - goal) % limit == 0 ? 0 : 1);
return cnt;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/07/PS/LeetCode/minimum-elements-to-add-to-form-a-given-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.