Minimum Elements to Add to Form a Given Sum LeetCode solution in C++

1
class Solution {
2
public:
3
int minElements(vector<int> &nums, int limit, int goal) {
4
// just calculate how many limit values to be added to the array to make our
5
// currSum close to the goal
6
long int currSum = 0;
7
for (auto ele : nums) currSum += ele;
8
long int remaining = abs(currSum - goal);
9
if (remaining == 0) return 0;
10
long int res = (remaining / limit);
11
// if remaining exists still after adding limit k times
12
// ex - remaining - 7 limit -3 we have to add a 1 after adding two times of
13
// limit values (6)
14
res += (remaining % limit != 0) ? 1 : 0;
15
return res;
16
}
17
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0