Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
