# Program to find maximum number of groups getting fresh donuts in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a value batchSize and an array group where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. So there is a donuts shop that bakes donuts in batches of given batchSize. But they have one rule, they must serve all of the donuts of a batch before serving any donuts of the next batch. And each customer will get exactly one donut. When a group enters the shop, all customers of that group must be served before addressing any next groups. One group may happy if they all get fresh donuts. (In other words the first customer of the group does not accept a donut that was left over from the last group).

We can rearrange the groups, and finally we have to find the maximum possible number of happy groups after rearranging the groups.

So, if the input is like batchSize = 4 groups = [2,1,8,4,3], then the output will be 4 because we can rearrange them like [8,4,2,3,1] so first, second, third and fourth groups are happy. We can make two batches of donuts for first group, one batch for second group, and make one batch then serve it to third group and one for the fourth.

To solve this, we will follow these steps −

• l := a list with (g mod batchSize) for all g in groups

• count := a map containing frequency of elements of l

• g := a list of count[i] for all i in range 0 to batchSize

• Define a function dp() . This will take sm, t

• if maximum of t is same as 0, then

• return 0

• ans := 0

• arr := t

• for k in range 0 to batchSize - 1, do

• if arr[k] is same as 0, then

• go for next iteration

• arr[k] := arr[k] - 1

• ans := maximum of ans and dp((sm + k) mod batchSize, arr)

• arr[k] := arr[k] + 1

• return ans +(1 if sm is same as 0 otherwise 0)

• From the main method return dp(0, g)

## Example

Let us see the following implementation to get better understanding

from collections import Counter
def solve(batchSize, groups):
l = [g % batchSize for g in groups]
count = Counter(l)
g = [count[i] for i in range(batchSize)]

def dp(sm, t):
if max(t) == 0:
return 0

ans, arr = 0, list(t)
for k in range(batchSize):
if arr[k] == 0:
continue
arr[k] -= 1
ans = max(ans, dp((sm + k) % batchSize, arr))
arr[k] += 1
return ans + (sm == 0)

return dp(0, g)

batchSize = 4
groups = [2,1,8,4,3]
print(solve(batchSize, groups))

## Input

4, [2,1,8,4,3]


## Output

4
Updated on 08-Oct-2021 07:58:58