Program to find maximum number of K-sized groups with distinct type items are possible in Python

Suppose we have a list of numbers called counts where counts[i] represents the number of items are of type i. We also have another value k. We have to find the maximum number of groups of size k we can find, such that each group must have items of distinct types.

So, if the input is like counts = [2, 3, 5, 3] k = 2, then the output will be 6, because let four types of items are represented by a, b, c, d respectively. We can have the following groups of k = 2, where all elements are of distinct types: [(c, a), (b, a), (c, b), (c, b), (d, a), (d, a)].

To solve this, we will follow these steps −

  • Define a function possible(). This will take counts, groups, k
  • required := groups * k
  • for i in range 0 to size of counts, do
    • temp := minimum of counts[i], groups and required
    • required := required - temp
    • if required is same as 0, then
      • return True
  • return False
  • Define a function solve() . This will take counts, k
  • res := 0
  • l := 0
  • r := sum of all elements present in counts
  • while l
  • m := l + floor of (r - l) / 2
  • if possible(counts, m, k) is true, then
    • l := m + 1
    • res := maximum of res and m
  • otherwise,
    • r := m - 1
  • return res
  • Example

    Let us see the following implementation to get better understanding −

    def possible(counts, groups, k):
       required = groups * k
       for i in range(len(counts)):
          temp = min(counts[i], groups, required)
          required -= temp
          if required == 0:
             return True
       return False
    
    def solve(counts, k):
       res = 0
       l = 0
       r = sum(counts)
       while l 

    Input

    [2, 3, 5, 3], 2

    Output

    6
    Updated on: 2021-10-19T09:59:09+05:30

    1K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements