MediumNo. 1785

Minimum Elements to Add to Form a Given Sum — LeetCode 1785 Python Solution

Pattern
Greedy
Topics
Greedy, Array
Reading time
2 min

The problem

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.

Example

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.

Python solution

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

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1785. Minimum Elements to Add to Form a Given Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1792Maximum Average Pass RatioMedium
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium
0324Wiggle Sort IIMedium

Frequently asked questions

How hard is LeetCode 1785. Minimum Elements to Add to Form a Given Sum?

LeetCode 1785. Minimum Elements to Add to Form a Given Sum is rated Medium on LeetCode.

What is the time complexity of LeetCode 1785. Minimum Elements to Add to Form a Given Sum?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1785. Minimum Elements to Add to Form a Given Sum?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1785. Minimum Elements to Add to Form a Given Sum cover?

LeetCode 1785. Minimum Elements to Add to Form a Given Sum is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.