
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find minimum element addition needed to get target sum in Python
Suppose we have list of numbers called nums and another two variables k and t. Let us consider an operation where we choose an element say e in range [-k, k] and insert it to nums at the end. We have to find the minimum number of operations needed so the sum of the nums equals to target.
So, if the input is like nums = [3, 1] k = 4 t = 19, then the output will be 4 because we can add like [3, 1, 4, 4, 4, 3] to get the sum 19.
To solve this, we will follow these steps −
total := sum of all elements present in nums
diff := |t - total|
result := floor of (diff/k)
if result * k is not same as diff, then
result := result + 1
return result
Example
Let us see the following implementation to get better understanding
def solve(nums, k, t): total = sum(nums) diff = abs(t - total) result = diff // k if result * k != diff: result = result + 1 return result nums = [3, 1] k = 4 t = 19 print(solve(nums, k, t))
Input
[3, 1], 4, 19
Output
4
- Related Articles
- Program to find minimum distance to the target element using Python
- Program to find minimum operations needed to make two arrays sum equal in Python
- C++ program to count number of minimum coins needed to get sum k
- C++ program to find minimum number of punches are needed to make way to reach target
- Program to find minimum swaps needed to group all 1s together in Python
- Python Program To Get Minimum Element For String Construction
- Program to find minimum number of rocketships needed for rescue in Python
- Program to find minimum costs needed to fill fruits in optimized way in Python
- Program to find minimum amount needed to be paid all good performers in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find minimum absolute sum difference in Python
- Program to find minimum jump needed to return from a folder to home in Python
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to find minimum numbers of function calls to make target array using Python
- Program to find lowest sum of pairs greater than given target in Python

Advertisements