Maximum Number of Groups Getting Fresh Donuts - Problem

There is a donut shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch.

You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.

When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.

You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.

Input & Output

Example 1 — Basic Case
$ Input: batchSize = 3, groups = [1,2,3,1,2]
Output: 4
💡 Note: Optimal arrangement [3,1,2,1,2]: Group 3 (remainder 0) is happy, group 1 starts fresh (remainder was 0), group 2 starts fresh (remainder was 1), group 1 starts fresh (remainder was 0), group 2 is not fresh (remainder was 1). Total: 4 happy groups.
Example 2 — Small Batch
$ Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]
Output: 4
💡 Note: Groups with remainder 0 (like 4,8) are always happy. Groups with remainders that sum to batchSize can be paired strategically.
Example 3 — All Same Remainder
$ Input: batchSize = 2, groups = [1,1,1,1]
Output: 2
💡 Note: All groups have remainder 1. First group is happy, second is not (remainder 1), third is happy (remainder 0 after second), fourth is not. Maximum: 2 happy groups.

Constraints

  • 1 ≤ batchSize ≤ 9
  • 1 ≤ groups.length ≤ 30
  • 1 ≤ groups[i] ≤ 109

Visualization

Tap to expand
Maximum Groups Getting Fresh Donuts (batchSize=3)Input Groups12312Optimal Arrangement31212R=0 HappyR=0 HappyR=1 HappyR=0 HappyR=1 Not HappyDonut Batch Tracking (batchSize = 3)Batch 1: 3 donutsBatch 2: 3 donutsBatch 3: 3 donutsBatch 4: 3 donutsUsed: 3, Left: 0Used: 1, Left: 2Used: 3, Left: 0Used: 1, Left: 2Result: 4 Happy Groups(Groups that started fresh)
Understanding the Visualization
1
Input
batchSize=3, groups=[1,2,3,1,2]
2
Process
Arrange groups to maximize those starting with fresh donuts
3
Output
Maximum 4 groups can be happy
Key Takeaway
🎯 Key Insight: Group happiness depends only on remainder modulo batchSize - groups are happy when remainder=0
Asked in
Google 8 Microsoft 5
12.9K Views
Medium Frequency
~35 min Avg. Time
423 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen