Program to find minimum elements to add to form a given sum in Python

Suppose we have an array called nums and two values limit and goal. The array is special because |nums[i]|

So, if the input is like nums = [2,-2,2], limit = 3, goal = -4, then the output will be 2 because we can add two (-3)s, so that the array will be [2,-2,2,-3,-3]

To solve this, we will follow these steps −

  • s := sum of all elements present in nums

  • ab := |goal - s|

  • return the ceiling of (ab / limit)

Example

Let us see the following implementation to get better understanding −

from math import ceil

def solve(nums, limit, goal):
   s = sum(nums)
   ab = abs(goal - s)
   return ceil(ab / limit)

nums = [2,-2,2]
limit = 3
goal = -4
print(solve(nums, limit, goal))

Input

[2,-2,2], 3, -4

Output

2.0
Updated on: 2021-10-06T11:17:31+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements