- 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
Check if the given array can be reduced to zeros with the given operation performed given number of times in Python
Suppose we have an array nums and a value k, we have to check whether the elements in nums can be made 0 by performing the following operation exactly k number of times or not.
- Operation: The smallest element from the nums will be subtracted from all of the non-zero values of nums.
So, if the input is like nums [2, 2, 3, 5] k = 3, then the output will be True because at first delete 2 from array, so the array will be [0, 0, 1, 3], then remove 1 to get [0, 0, 0, 2], then again delete 2 to get [0, 0, 0, 0].
To solve this, we will follow these steps −
- if there are k number of distinct elements, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(nums, k): distinct = set(nums) if len(distinct) == k: return True return False nums = [2, 2, 3, 4] k = 3 print(solve(nums, k))
Input
[2, 2, 3, 4], 3
Output
True
Advertisements