- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements
To Continue Learning Please Login
Login with Google