# Program to find minimum element addition needed to get target sum in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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
Updated on 11-Oct-2021 06:23:35