![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]| <= 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)
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
Advertisements