Check if the given array can be reduced to zeros with the given operation performed given number of times in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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
raja
Published on 15-Jan-2021 11:12:29
Advertisements