Skip to content

1785. Minimum Elements to Add to Form a Given Sum

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int minElements(vector<int>& nums, int limit, int goal) {
    const long sum = accumulate(nums.begin(), nums.end(), 0L);
    const double diff = abs(goal - sum);
    return ceil(diff / limit);
  }
};
1
2
3
4
5
6
7
class Solution {
  public int minElements(int[] nums, int limit, int goal) {
    final long sum = Arrays.stream(nums).asLongStream().sum();
    final double diff = Math.abs(goal - sum);
    return (int) Math.ceil(diff / limit);
  }
}