Remove One to Make Average k in Python


Suppose we have a list of numbers called nums and an integer k, we have to check whether we can remove exactly one element from the list to make the average equal to exactly k. Now we have to keep in mind that, there are some constraints −

  • 2 ≤ n ≤ 1,000 where n is number of elements of nums list
  • nums[i], k ≤ 1,000,000

So, if the input is like [5,3,2,4,6,10], k = 4, then the output will be True as if we remove 10, then the average of elements will be (5+3+2+4+6)/5 = 4, this is same as k.

To solve this, we will follow these steps −

  • s:= total sum of all elements in nums
  • t := k*(size of nums - 1)
  • for each i in nums, do
    • if s-i is same as t, then
      • return True
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      s=sum(nums)
      t = k*(len(nums)-1)
      for i in nums:
         if s-i == t:
            return True
      return False
ob = Solution()
nums = [5,3,2,4,6,10]
k = 4
print(ob.solve(nums, k))

Input

[5,3,2,4,6,10], 4

Output

True

Updated on: 23-Sep-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements