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

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums and two values limit and goal. The array is special because |nums[i]| <= limit for all i from 0 to size of array - 1. We have to find the minimum number of elements to be inserted to make the sum of the array same as goal. Array element should not exceed limit value.

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)


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))


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


Published on 06-Oct-2021 11:17:31