1785. Minimum Elements to Add to Form a Given Sum LeetCode Solution
In this guide, you will get 1785. Minimum Elements to Add to Form a Given Sum LeetCode Solution with the best time and space complexity. The solution to Minimum Elements to Add to Form a Given Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Minimum Elements to Add to Form a Given Sum solution in C++
- Minimum Elements to Add to Form a Given Sum solution in Java
- Minimum Elements to Add to Form a Given Sum solution in Python
- Additional Resources
Problem Statement of 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]) = 0, and -x otherwise.
Example 1:
Input: nums = [1,-1,1], limit = 3, goal = -4
Output: 2
Explanation: You can add -2 and -3, then the sum of the array will be 1 – 1 + 1 – 2 – 3 = -4.
Example 2:
Input: nums = [1,-10,9,1], limit = 100, goal = 0
Output: 1
Constraints:
1 <= nums.length <= 105
1 <= limit <= 106
-limit <= nums[i] <= limit
-109 <= goal <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1785. Minimum Elements to Add to Form a Given Sum LeetCode Solution in C++
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);
}
};
/* code provided by PROGIEZ */
1785. Minimum Elements to Add to Form a Given Sum LeetCode Solution in Java
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);
}
}
// code provided by PROGIEZ
1785. Minimum Elements to Add to Form a Given Sum LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.