1785. Minimum Elements to Add to Form a Given Sum¶ Time: $O(n)$ Space: $O(1)$ C++Java 1 2 3 4 5 6 7 8class 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 7class 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); } }