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