# Program to reduce list by given operation and find smallest remaining number in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of positive numbers called nums. Now consider an operation where we remove any two values a and b where a ≤ b and if a < b is valid, then insert back b-a into the list nums. If we can perform any number of operations, we have to find the smallest remaining number we can get. If the list becomes empty, then simply return 0.

So, if the input is like nums = [2, 4, 5], then the output will be 1, because, we can select 4 and 5 then insert back 1 to get [2, 1]. Now pick 2 and 1 to get [1].

To solve this, we will follow these steps −

• s := sum of all elements present in nums
• Define a function f() . This will take i, s
• if i >= size of nums , then
• return s
• n := nums[i]
• if s - 2 * n < 0, then
• return f(i + 1, s)
• return minimum of f(i + 1, s - 2 * n) and f(i + 1, s)
• from the main method return f(0, s)

## Example

Let us see the following implementation to get better understanding −

def solve(nums):
s = sum(nums)

def f(i, s):
if i >= len(nums):
return s
n = nums[i]
if s - 2 * n < 0:
return f(i + 1, s)
return min(f(i + 1, s - 2 * n), f(i + 1, s))

return f(0, s)

nums = [2, 4, 5]
print(solve(nums))

## Input

[2, 4, 5]

## Output

1
Published on 18-Oct-2021 12:04:57