LeetCode 1785. Minimum Elements to Add to Form a Given Sum Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1785. Minimum Elements to Add to Form a Given Sum

Description

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.

 

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

Solutions

Solution 1: Greedy

First, we calculate the sum of the array elements s, and then calculate the difference d between s and goal.

The number of elements to be added is the absolute value of d divided by limit and rounded up, that is, \lceil |d|limit \rceil.

Note that in this problem, the data range of array elements is [-106, 106], the maximum number of elements is 105, the total sum s and the difference d may exceed the range of 32-bit integers, so we need to use 64-bit integers.

The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the array nums.

PythonJavaC++GoTypeScriptRustC
class Solution: def minElements(self, nums: List[int], limit: int, goal: int) -> int: d = abs(sum(nums) - goal) return (d + limit - 1) // limit(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !