- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- Related Questions & Answers
- Python program to find the smallest number in a list
- Program to find nth smallest number from a given matrix in Python
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- C++ Program to find the smallest digit in a given number
- Program to perform given operation with each element of a list and given value in Python
- Reduce a number to 1 by performing given operations in C++
- Program to make all elements equal by performing given operation in Python
- Find smallest permutation of given number in C++
- 8085 Program to find the smallest number
- Python Program for Smallest K digit number divisible by X
- Program to find smallest string with a given numeric value in Python
- Program to find minimum cost to reduce a list into one integer in Python
- Python program to find the number occurring odd number of times using Lambda expression and reduce function
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Find smallest number with given number of digits and sum of digits in C++

Advertisements