Program to find number of items left after selling n items in python


Suppose we have a list of numbers called items and another value n. A salesman has items in a bag with random IDs. The salesman can delete as many as n items from the bag. We have to find the minimum number of different IDs in the bag after n removals.

So, if the input is like items = [2, 2, 6, 6] n = 2, then the output will be 1 as we he can sell two items with ID 2 or ID 6, then only items with single target will be there.

To solve this, we will follow these steps:

  • c := frequency of each element present in items
  • ans := size of c
  • freq := sort the list of all frequencies in c
  • i := 0
  • while i < size of freq, do
    • if freq[i] <= n, then
      • n := n - freq[i]
      • ans := ans - 1
    • otherwise,
      • return ans
    • i := i + 1
  • return 0

Let us see the following implementation to get better understanding:

Example

Live Demo

from collections import Counter

class Solution:
   def solve(self, items, n):
      c = Counter(items)
      ans = len(c)
      freq = sorted(c.values())
      i = 0
      while i < len(freq):
         if freq[i] <= n:
            n -= freq[i]
            ans -= 1
         else:
            return ans
         i += 1
      return 0

ob = Solution()
items = [2, 2, 6, 6]
n = 2
print(ob.solve(items, n))

Input

[2, 2, 6, 6], 2

Output

1

Updated on: 26-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements